Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB5,VB6
Expertise: Intermediate
Dec 18, 1999

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 module
Public 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 = A
End 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.

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.

Francesco Balena
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date