Saturday, December 4, 2010

Property Set/Let/Get


Instead of assigning values to public properties in the class, you might want to declare values in the class as private. Then to alter the value you need the property set statement (well OK statement is a bad choice of words - Set is a method). This moves the assignment so that it takes place inside the class.


You might think this is a waste of time at first glance, after all, at the end of the day you are just setting a value in the class - public, private - you still get to change the value from outside.


But look at it like this - now you can write validation code to check that the assignment is legal and all that code can be hidden inside the class. If you use a public variable and you send in a duff value, there is nothing much the code inside the class can do to defend itself against your idiocy, so you would really have to do valdition in the code that is instantiating the class - that would mean copies of validation code all over the place. With property set you can do that validation once and it will always work. But there is another thing - and I find this is even more useful...You can use the property set statement to set more than one variable inside your class. Also you can have a write-only property by defining a Property Let procedure without a corresponding Property Get procedure. Write-only properties, however, are comparatively rare, and are used primarily to prevent access to sensitive information such as passwords.


Set is used for objects while Let and Get are used for Values


Extending our persona class described in the previous post, here is an example of using the property let/get statements:


As before save this in an include file:


Class Persona

Private ftelephone

Public age

Public gender


public property let telephone(ptelephone)

ftelephone = ptelephone

end property


public property get telephone()

telephone = ftelephone

end property


End Class


Then use this class by instantiating a copy of it in your classic ASP page:


Set Freda = New persona


With Freda

.age = 23

.gender = "female"

.telephone ="995129993"

End With


response.write("Freda is a " & Freda.age & " year old " & Freda.gender & " phone: " & Freda.telephone)


 


 




No comments: