B
Berlin Brown
The short version
-----------------
Should a class access its own private members with getters & setters
or instead directly access those members?
Assume the class has getters & setters already so that outside classes
can access those members.
The long version
----------------
Which is preferred? Style A:
public class Foo
{
private int bar = 0;
public int getBar() { return bar; }
public void setBar(int bar) { this.bar = bar; }
public void multiplyByTen()
{
setBar(getBar() * 10);
}
}
Or style B:
public class Foo
{
private int bar = 0;
public int getBar() { return bar; }
public void setBar(int bar) { this.bar = bar; }
public void multiplyByTen()
{
bar *= 10;
}
}
This is obviously a trivial example but try to imagine it within the
context of a bigger and more complex class.
Assume that other classes will be using getBar() and setBar() and so
those methods would exist anyway.
Which style is preferred? And why? Does Sun or any other authority
on the matter have an opinion? Any articles on the subject? (A brief
web search didn't turn up much.) Any opinions from the authors of Java
books?
Thanks in advance for any input/suggestions/ideas/opinions/etc.! The
developers at my company are well torn on this issue and getting a
'authoritative' opinion would be very helpful.
I would go with the one that makes more sense. If I am searching
through a lot of code and I see:
setBar(getBar() * 10); what does that mean?
If I see:
bar = bar * 10, oh I got it. You are setting some global variable.
Plus the fact, Ideally, you want to get your code out and test it. If
you are spending time deciding on style issues. I think that is time
wasted. Could be wrong?