...
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 index key in the HashMap
. Make sure that you do not return references to private mutable objects from accessor methods (see OBJ05-J. Defensively copy private mutable class members before returning their references for details).
Exceptions
OBJ01-EX0: According Fields with no associated behavior or invariants can be public. According to Sun's Code Conventions document [Conventions 2009]:
One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. In other words, if you would have used a
struct
instead of a class (if Java supportedstruct
), then it's appropriate to make the class's instance variablespublic
.
OBJ01-EX1: "If Fields in a class is package-private class or is in a private
nested class , there may be pubic or protected. There is nothing inherently wrong with exposing its data fields—assuming they do an adequate job of describing the abstraction provided by the class. This approach generates less visual clutter than the accessor-method approachdeclaring fields to be public or protected in these cases. Eliminating accessor-methods generally improves the readability of the code, both in the class definition and in the client code that uses it" client [Bloch 2008]. This exception applies to both mutable and immutable fields.
OBJ01-EX2: Static final fields that contain mathematical or reference immutable constants may be declared public or protected.
Risk Assessment
Failing to limit field accessibility can defeat encapsulation, allow attackers to manipulate fields to violate class invariants, or allow these fields to be corrupted as the result of concurrent accesses from multiple threads.
...