If I have an instance variable which has private visibility should I use a setter to change its value, or simply change the value directly?
The instance variable in this example will only ever be changed in this class, and thus the setter would be private. I assume using the setter is the right way as it localizes how/when it is changed, but its just something that is bugging me for some reason!
Please see below for code which may help convey my question clearer
public class A {
private int i;
public A() {
i = 5
}
private void doSomeCalculationsA() {
//work done here which results in the value of i being directly changed
i = 7
}
private void doSomeCalculationsB() {
//work done here which results in change value of i being changed via the setter
setI(5)
}
private void setI(int newValue) {
i = newValue;
}
}
I tend to think that simpler is clearer most of the time. If your setI is only ever going to be a setter, I wouldn't have it. If you want to imply that the method could do something more one day, you might consider having one, but for me YAGNI is the best approach.
"Always implement things when you actually need them, never when you just foresee that you need them."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With