Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should a class use its own getters/setters vs accessing the members directly?

When generating setters and getters in Eclipse one of the options is to use the getters and setters within the class rather than accessing the class members directly. Is this level of class internal encapsulation useful or is it taking a good idea one step too far?

DUPE: Should you use accessor properties from within the class, or just from outside of the class?

like image 744
stimms Avatar asked Feb 25 '09 14:02

stimms


3 Answers

I think it's a good idea if you want the potential side-effects to occur - validation, logging etc. (In C# I'd like to be able to declare a variable and property and say that the only access to the variable is through the property.)

Occasionally you may well find you need to set the variable directly precisely because you don't want the side-effects. For instance, you may need to set two variables together, and both the "before" and the "after" states are valid, but setting either property individually would make validation blow up.

like image 193
Jon Skeet Avatar answered Nov 09 '22 04:11

Jon Skeet


It can be useful, if you allow derived classes to re-define your getters. So, using getters even from inside the class will keep your design extensible.

In my opinion this is something that needs to be defined in the coding guidelines.

like image 39
Joachim Sauer Avatar answered Nov 09 '22 03:11

Joachim Sauer


The short answer is "it depends" :)

Eric Lippert has an excellent article on Automatic vs. Explicit properties that deals with this issue, albeit from a slightly different angle.

Essentially, the question you need to ask is:

"From within the class, [are] the desired semantics of accessing this ... property different from the desired semantics of accessing the property from the outside?"

If the semantics are the same, your class should use its own properties. If the semantics are different, your class will need to directly manipulate the backing fields.

like image 31
AwesomeTown Avatar answered Nov 09 '22 03:11

AwesomeTown