...
Code Block | ||
---|---|---|
| ||
public class Widget { public int total; // Number of elements void add() { if (total < Integer.MAX_VALUE) { total++; // ... } else { throw new ArithmeticException("Overflow"); } } void remove() { if (total > Integer.MIN_VALUE0) { total--; // ... } else { throw new ArithmeticException("Overflow"); } } } |
Wiki Markup |
---|
As a {{public}} data member, {{total}} can be altered by external code, independent of the {{add()}} and {{remove()}} methods. It is a bad practice to expose both mutable and immutable fields from a {{public}} class \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. |
Compliant Solution (
...
private
)
This compliant solution declares total
as private
and provides a public
accessor so that the required member can be accessed beyond the current package. The add()
and remove()
methods modify its value without violating any class invariants.
Note that accessor functions should be careful about providing references to private mutable objects; see OBJ11-J. Defensively copy private mutable class members before returning their references for details.
Code Block | ||
---|---|---|
| ||
public class Widget { private int total; // Declared private public int getTotal () { return total; } // definitions for add() and remove() remain the same } |
It is good practice to use wrapper methods , such as add()
, remove()
, and getTotal()
, to manipulate the private internal state, because the methods can perform additional functions, such as input validation and security manager checks, prior to manipulating the state.
...