...
Code Block | ||
---|---|---|
| ||
public class Widget { public int total; void add() { if (total < Integer.MAX_VALUE) { throw new ArithmeticException("Overflow"); } total++; // ... } throw new ArithmeticException("Overflow"); } void remove() { if (total > Integer.MIN_VALUE) { total--; // ... } throw new ArithmeticException("Overflow"); } } public int getTotal total--;() { // ...return total; } } |
Compliant Solution
This compliant solution declares total
as private
and provides a public
accessor so that the class can be accessed beyond the current package. The method add()
modifies its value without violating any class invariants.
Code Block | ||
---|---|---|
| ||
public class Widget { private int total; // void add() {Declared private void if (total < Integer.MAX_VALUE) { throw new ArithmeticException("Overflow"); }add() { total++; // ... } void remove() { if (total > Integer.MIN_VALUE) { throw new ArithmeticException("Overflow"); } total--; // ... } public int getTotal () { return total;// ... } } |
It is good practice to use wrapper methods such as add()
, remove()
and getTotal
, to manipulate private internal state because the methods can perform additional functions such as input validation and security manager checks prior to manipulating the state.
...