开发者

Is it bad practice to access a data member directly?

开发者 https://www.devze.com 2023-01-08 18:30 出处:网络
I recall being told by a professor the following is bad practice. But 开发者_Go百科it makes stepping through code a lot less tedious. I\'m just solicting comments on pros and cons:

I recall being told by a professor the following is bad practice. But 开发者_Go百科it makes stepping through code a lot less tedious. I'm just solicting comments on pros and cons:

Friend Class MyClass
 Private isEmpty As Boolean
 Public Property IsEmpty() As Boolean
  Get
   Return isEmpty
  End Get
  Set(ByVal Value As Integer)
   isEmpty = value
  End Set
 End Property
 Public Sub MyMethod()
  ''//Is this more correct:
  If Me.IsEmpty() Then
   ''//Do something.
  End If
  ''//Is this bad practice?:
  If isEmpty Then 
   ''//Do something.
  End If
 End Sub
End Class 


If you have set up a property to access the private member variable "isEmpty", than yes, I would use the property inside of the class itself unless there is a darn good reason for not doing so.

The reason being that you may at a later point in time need to do more work when the property is set (or possibly when retrieved), and then you would likely have to find all the references to the private member variable in your class and change them to access the property instead.


To add to Ed's answer, some IDE's allow you to set a flag saying you do not want to dive into property getter/setters like this. I don't know about VB but C#/VS2008 will do this. So that takes 'stepping thru the code' convenience out of the equation in deciding what is the right thing to do.


It really gets down it instinct and experience as a developer. If you're super positive you'll never need to do any processing on that property, then I say access it directly. Otherwise write the wrapper, it doesn't really hurt.

Although, it has never been that big a deal to add it later either. I wouldn't get too religious about either method.

0

精彩评论

暂无评论...
验证码 换一张
取 消