...
Wiki Markup |
---|
However, as a {{public}} data member, {{total}} can be altered by external code, independent of these actions. This noncompliant code example violates the condition that {{public}} classes must not expose data members by declaring them {{public}}. It is a bad practice to expose both mutable and immutable fields from a {{public}} class \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. |
...
Code Block | ||
---|---|---|
| ||
public class Widget { private int total; // Declared private voidpublic int getTotal add() { // ...return total; } void remove() { // ... definitions } public int getTotal for add() and remove() { remain return total; }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.
...