If the getter/setter exist, always use them. getFoo
and setFoo
effectively define a property named "Foo", which is conceptually different from your variable foo
. foo
is just the variable holding the current value of that property, and could be considered as belonging to the property.
Keep in mind, though, a property doesn't have to just get/set its backing variable. It could also validate the value you pass in before setting it. It could synchronize access to the variable. And/or in the future, a setter might alter the characteristics of some other thing, and the getter could return the current state of that other thing, without even needing the backing variable. By setting the variable directly, you create compatibility issues in the case where the property is/would be changed to do any of that in the future.
If, however, you know that setFoo
does (and, in the near future, will still do) nothing other than set a variable named foo
, then it'd actually be better to not have a getter/setter. They're not any cleaner, or more readable, and they're certainly not more efficient; a = 3; doStuffWith(a);
beats setA(3); doStuffWith(getA());
on all counts. And their absence rids you of the conceptual baggage of a property where you only need a variable. Only add the getter/setter when you need (or definitely will need very soon) the special behavior a property can provide. But once you've added them, use them everywhere.