By the theories of OO we should use the private member within the class but not the Property.
But properties can be used to validate a value before being assigned to the private variable.
My personal idea is, when validation is required, have a separate private method to do validation and call that method inside the property’s setter and else where.
i.e:
Private m_name As String
Public Property Name() As String
Get
Return m_name
End Get
Set(ByVal Value As String)
Dim validValue As Boolean
validValue = ValidateName(Value)
If validValue Then
m_name = Value
End If
End Set
End Property
Private Function ValidateName(ByVal p_name As String) As Boolean
If p_name.Length < validvalue =" ValidateName(p_name)" m_name =" p_name">
Or should we set the property in side SetName method?
What is the best practice to use in such situations?
Please send in your ideas
Hi Mahasen,
ReplyDeleteMy vote to you. It is my personal belief that when there is a specific action associated while accessing/retrieving value from a variable, we should prefer member functions. So considering your example as Validate() action has to be performed before setting the value to m_name, I think SetName() should be used for both checking the validity and assigning the value using Name Property.
Public Sub SetName(ByVal p_name As String)
Dim validValue As Boolean
validValue = ValidateName(p_name)
If validValue Then
Name = p_name
End If
End Sub
Bottom line is Methods represent actions and Properties represent data. Never set/get a value to private variable if ever a corresponding Public property for that variable is available. And a Property should not be used if the scope of the variable is confined to the same class.
Please validate me if you have a different view.
thanks and regards,
Ch. Chandra Sekhar,
Team Virtusa.
I'm also agree with u guys.
ReplyDeleteAnd I have got another problem. I have a class that hold common things using in the application. There is a static variable. I declare it as public and didn't use properties that give access to it. Why I did like that is I think because anyway we can't change that variable, no need of using properties.
Pls update me from ur ideas.
Madhawa
Hi Madhawa,
ReplyDeleteThe concept of properties comes to objects, static is to classes. so when you use static members you do not have to implement them as getters & setters.
But being static does not mean that it couldn't be written to, you have to use "readonly" if you want to prevent it from being written to - in properties we do it by not giving a setter.
hope i'm clear enough.
Thanks.