Question OO Design: Use Getters/Setters Interally?

VentureFree

Well-known member
Joined
Jan 9, 2008
Messages
54
Programming Experience
5-10
This is probably a stupid question, but when accessing an attribute from within a class is it generally better to access the private variable directly, or access it using the getter/setter? Of course the whole point of encapsulating attributes is to allow changes to the underlying code without affecting anything that uses it. Should that also apply to the class itself? Or is it a case where the class should have full knowledge, and so shouldn't have to use the getters/setters?
 
It really depends on the situation. If you have no additional logic in your properties then there's no actual difference. In that case, I tend to use the fields rather than the properties.

If you do have additional logic in your properties then it's a case of whether you want that logic executed or not. It might be different in different places. For instance, you wouldn't want property changed events raised in a constructor, so you'd set fields in the constructor. In other methods you may want events raised, so using properties is appropriate.
 
Back
Top