Choosing Between Methods or Properties
As you may pointed our earlier. Properties is like a function. So
how can we know when we must implement property or a function. To tell you
honestly, their is no universal rule concerning this scenario, but usually
programmer implement a properties when a routine serves mostly to return a value
stored inside the class and can be quickly and easily reevaluated.
When the routine servers mostly to evaluate a complex value, they use function.
If programmer thinks that in the future the value returned by the routine could
be assigned to, they use Property Get procedure and gives them a chance
to add a Property Let when its time to implement one.
Let's make an example. Earlier we implement a Property Get procedure for our
class member FullName. How can we make our class more useable in a long
run by providing a Property Let. This way we can have two way of assign a
value to FirstName and LastName property. A possible solution might look
like this:
Property Let FullName(ByVal strNewValue As String)
' Return the full name of Student object
Dim aStrName() As String
' Split the argument pass (strNewValue)
aStrName() = Split(strNewValue)
' Raise an error if an FirstName or LastName is empty
If UBound(aStrName) = 0 Then Err.Raise 5
FirstName = aStrName(0)
LastName = aStrName(1)
End Property
|
You can directly assign a value to FirstName and LastName property as shown
below:
objStudent.FullName = "Cathrina Anniversario"
'try getting the Student property FirstName and LastName
MsgBox objStudent.FirstName 'Invoke Property Get FirstName
MsgBox objStudent.LastName 'Invoke Property Get LastName
|
As you can see, even if we didn't assign a value to the Student FirstName
and LastName property explicitly, our new FullName property does
the job. This is other nice thing you can do with class property