Properties
State information of an object is generally not directly available to other classes and users. As you learned earlier, it's good practice to make member data private and provide accessors when you need to give access to other classes and users.
The best approach to creating accessors for member data is to define properties for each member variable that you want to allow access. Properties are special in the way they are defined and implemented. The following code segment shows how the MsgText() property is defined in the SimpleMsg class:
Class SimpleMsg 'member variable to store the message text Private strMessage As String 'property to allow get/set functionality on 'strMessage member variable Public Property MsgText() As String Get MsgText = strMessage End Get Set(ByVal Value As String) strMessage = Value End Set End Property End Class
The state information for the SimpleMsg class is the strMessage member variable. The property, MsgText(), provides access to retrieve and set the value of the strMessage member by implementing Get and Set.
Declaring a property is similar to declaring a function, except that Property is specified for the type of method. The return typeString, in this caseis defined the same as with a function declaration.
Within the property declaration, Get is defined for all properties that allow access to the state value. You don't need to provide access to the value if you want a WriteOnly property. Set is defined for all properties in which you allow state value changes. If the property is declared as ReadOnly, Set isn't defined.
Properties provide a clean way of implementing the same functionality that's available in object-oriented programming: You declare an overloaded subroutine and function. The same functionality is implemented in the following code:
Class SimpleMsg 'member variable to store the message text Private strMessage As String Public Function MsgText() As String MsgText = strMessage End Function Public Sub MsgText(ByVal Value As String) strMessage = Value End Sub End Class
The differences in this implementation aren't as obvious until you use the object. With the property declared, you assign the property value as follows:
MyMsg.MsgText = "Hello"The second method of implementation doesn't allow for direct assignment of the property because you defined a subroutine for the assignment. The following code shows how you perform the direct assignment:
MyMsg.MsgText("Hello")In the second method, what's being done isn't obvious and therefore not self-documenting, which is a goal of good source code design. Therefore, if you declare and use properties instead of subroutines and functions, you can produce better code while effectively providing the same functionality.