Ren wrote:
<snip>
I'm still rather new at vb.net and would like to know the proper way to access
private varibables in a class. Do I access the variable directly or do I use
the public property?
public class MyClass
private _variableName as integer
public property VariableName as integer
<snip> end property
public sub DoSomething ()
' do I use _variableName or
' do I use VariableName"
end sub
end class
Properties were created to protect, and even hide, the internal
structure of the object from the outside world. Ideally, only the
object itself should know about it's internal fields and how they
relate to the exposed properties.
Besides, properties allow for side-effects to happen when a given field
is accessed. Therefore, a property actually encapsulates a behavior.
Now, it's a very common practice to expose internal fields -- that were
suposed to be public -- through properties, even though these
properties are only getters/setters (I'm talking about just those
properties that are both a getter and a setter for a given field). The
reasoning is: a) you must not expose your internal fields and b)
properties protect you by keeping your interface intact should the
internal workings of the object change.
But It turns out that I see more frequent changes to an in-progress
object interface than to the internals of the object, usually because
of unantecipated needs of the "external world" (from the object's
perspective), even though the internal structure of the object remains
more or less intact.
Considering this, and as a left over from the time when compilers
wouldn't be smart enough to inline the access to properties, my
personal practice goes against (although not religiously) accessing
internal fields via getter/setter properties.
I mean, the object is in a priviledged position to see these fields, so
it should also exercise direct access to them.
Therefore, internally I'd use mVariableName, instead of the related
properties.
Regards,
Branco.