...
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. Do not return references to private mutable class members for details).
Noncompliant Code Example (Public Final Array)
A nonzero-length array is always mutable. Declaring a public final array is a potential security risk as the array elements may be modified by a client.
Code Block | ||
---|---|---|
| ||
public final SomeType [] SOMETHINGS = { ... };
|
Compliant Solution (Copy the Array)
This compliant solution declares the array private and provides a public accessor method that returns a copy of the array:
Code Block | ||
---|---|---|
| ||
private final SomeType [] SOMETHINGS = { ... };
public final SomeType [] somethings() {
return SOMETHINGS.clone();
}
|
This approach prevents the elements of the class instance of the array from being modified by a client.
Compliant Solution (Construct an Immutable Object)
An alternative approach is to have a private array from which a public immutable list is contructed:
Code Block | ||
---|---|---|
| ||
private final SomeType [] THE_THINGS = { ... };
public final List<SomeType> SOMETHINGS =
Collections.unmodifiableList(Arrays.asList(THE_THINGS));
|
Neither the class instance field nor the public list can be modified by a client.
Exceptions
OBJ01-EX0: Fields with no associated behavior or invariants can be public. According to Sun's Code Conventions document [Conventions 2009]:
...
OBJ00-J. Limit the extensibility of classes and methods with invariants