When creating a class, the attributes (member variables/instance variables) were declared as Private, which requires writing two special procedures to access the data. Why go to this extra trouble? Why not just declare these as Public?
Printable View
When creating a class, the attributes (member variables/instance variables) were declared as Private, which requires writing two special procedures to access the data. Why go to this extra trouble? Why not just declare these as Public?
Because the Property Let/Get/Set accessors allow you to control what you deem as valid data.
VB Code:
'Public member Public SomeProp As Integer 'In some other project mClass.SomeProp = (-1)
If you only want a number between 1 and 10, then there is no way to let the user of the class know. But if you use accessors...
VB Code:
Private mSomeProp As Integer Public Property Let SomeProp(ByVal i As Integer) If i < 1 or i > 10 Then Err.Raise 5 'Raise some error mSomeProp = i 'Otherwise set the local value End Property
It also gives you the ability to perform other tasks internally based on the data.
VB Code:
Public Event NumberChanged() Private mSomeProp As Integer Public Property Let SomeProp(ByVal i As Integer) If i < 1 or i > 10 Then Err.Raise 5 'Raise some error mSomeProp = i 'Otherwise set the local value RaiseEvent NumberChanged() End Property
Using Public variables is generally considered bad practice. There's a couple of reasons for this, first of all if you use a Public variable you will not know when the value has been changed, however if you use a Property procedure the Let/Set procedure will be called when the property is changing value. This allows you to check if a proper value has been passed. Let's say that only a value between 1 and 10 is allowed, how can you then check if the new value is correct if you have declared a public Integer variable?
In some cases certain requirements might also be filled before the user of your class may change one property value. For example if you build a class that allows the user to upload/download files from a FTP server you should not be able to pass a file name before a connection to the server has been made.
Cheers,
Joacim
Is it still considered bad practice if it doesn't matter what data is put into that variable? I know such situations aren't common, but I've seen it occur a few times before.
If the data has no restrictions, then you might just want to use a UDT.Quote:
Originally posted by Hu Flung Dung
Is it still considered bad practice if it doesn't matter what data is put into that variable? I know such situations aren't common, but I've seen it occur a few times before.
i need some examples of how to deal with invalid data....
any ideas?