It is difficult to control how public or protected fields are accessed. Invariants cannot be enforced for public nonfinal fields, or final fields that reference a mutable object. A protected member of an exported class represents a public commitment to an implementation detail. Attackers can manipulate such fields to violate class invariants or they may be corrupted by multiple threads accessing them concurrently [Bloch 2008]. As a result, fields must be declared private or package-private.
...
Depending on the required functionality, accessor methods may return a copy of the HashMap
or a value contained by the HashMap
. This compliant solution adds an accessor method that returns the value of an element given its key in the HashMap
. Make sure that you do not return references to private mutable objects from accessor methods (see OBJ05-J. Defensively copy Do not return references to private mutable class members before returning their references for details).
Exceptions
OBJ01-EX0: Fields with no associated behavior or invariants can be public. According to Sun's Code Conventions document [Conventions 2009]:
...
Item 13, "Minimize the Accessibility of Classes and Members" | |
[JLS 2005] | |
Section 2.2, "Public Fields" |
...
OBJ00-J. Limit the extensibility of classes and methods with invariants