What to do with private fields with getters and setters in Java [duplicate]
https://softwareengineering.stackexchange.com/questions/78334
-
01-11-2019 - |
Question
This question already has an answer here:
When are Getters and Setters Justified is an excellent question which focuses on using getters and setters as part of the external interface.
What I am struggling with is ... by having getters and setters there is now multiple ways to update the state of the object since private fields can updated directly bypassing the setter or can be updated by the setter.
Take the example below ... _size is the private field and it has two methods getSize()
and setSize(int size)
. If incrementing _size is coded up like the increment
method, all is good. On the other hand, using increment2
can put Order into an illegal state.
Is there a way to prevent developers from accidentally bypassing the getter / setter and use the private fields directly!? If not, what convention should be used to ensure that the object is never put into an invalid state?
public class Order {
private int _size = 0;
public int getSize() {
return _size;
}
public void setSize(int size) {
if (_size < 0)
throw IllegalArgumentException("...")
_size = size;
}
public void increment(int increment) {
setSize(getSize() + increment);
}
public void increment2(int increment) {
_size = _size + increment;
}
}
No correct solution