views:

99

answers:

3

I recall being told by a professor the following is bad practice. But 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 
+4  A: 

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.

Ed Swangren
+3  A: 

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.

n8wrl
Yes, you can add an attribute, even in VB.
Steven Sudit
A: 

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.

Dan Williams
I understand what you're saying, Dan, but im my experience there is no such thing as "super positive you'll never..."
n8wrl
it reminds me of the surrogate key vs. natural key debate on the database side. Hum... now I'm reconsidering my answer :)
Dan Williams
Dan, there's no cost to using the property.
Steven Sudit
@Steven: Agreed. No cost, possible benefit. Seems like an easy choice.
Ed Swangren
"More code" is never "no cost."
Bob Riemersma
@Bob: There is no performance cost. As for "more code", all you have to do is use automatic backing fields.
Steven Sudit
@Bob Riemersma: Yes, because I am sure that this code is going to be executed on a microcontroller with 64k of memory.
Ed Swangren
You miss the point. More lines of code means more maintenance costs.
Bob Riemersma