Default Properties tend to hide programming mistakes

Default Properties tend to hide programming mistakes

Visual Basic lets you create a default property or method by simply selecting the “(Default)” item in the combo box that appear if you click the Advanced button in the Procedure Attributes dialog box. (You can display this dialog from the Tools menu, or by right-clicking on a property name in the right-most pane in the Object Browser.)

While default properties are cool and make your object easier to use, you should be at least aware that they have their downside as well, in that they tend to hide programming errors in the code that uses the object. To prove this, create a CPerson class module, then add a Name property using this single line of code:

' in the CPerson class modulePublic Name As String

Then write this code in a form module

Private Sub Command1_Click()    Dim A As New CPerson    Dim B As CPerson    Dim C As New CPerson    ' Create three variables that point to the same object    A.Name = "Joe Doe"    ' there is a mistake in the following lines: SET is missing    B = A    C = AEnd Sub

Because of the missing SET statements – by far the most common error when working with objects – the B=A statement raises error 91 “Object variable or With block variable not set”, whereas the C=A statement raises a more cryptic error 438 “Object doesn’t support this property or method”. This is OK, because we made a programming mistake and VB has been as kind.

However, if you now make Name the default property of the CPerson class, you’ll find that in some cases no error is raised, thus preventing the alarm bell from ringing in your head. In fact, while the B=A statement still raises error 91, the C=A assignment now executes flawlessly. Unfortunately, though, the results aren’t what you expected: VB has silently created a new instance of the CPerson class (the C variable) and has assigned it the default property of the object held in the A variable. In the end you have two objects instead of one, and the code isn’t doing what it was supposed to do.

See also  Does It Make Sense to Splurge on a Laptop?

The solution (sort of) is simple: don’t create default properties. Or at least, double-check that all assignments between objects are prefixed by the SET command.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist