...
Noncompliant Code Example (Public Mutable Field)
Programmers often incorrectly assume that declaring a field or variable final makes the referenced object immutable. Declaring variables that have a primitive type final does prevent changes to their values after initialization (by normal Java processing). However, when the field has a reference type, declaring the field final only makes the reference itself immutable. The final clause has no effect on the referenced object. According to the Java Language Specification, §4.12.4, "final Variables" [JLS 2013],
If a
final
variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.
This noncompliant code example declares a static final This noncompliant code example shows a static mutable hash map with public accessibility:
...
Providing direct access to the array objects themselves is safe because String is immutable.
Compliant Solution (Clone the Array)
...
As before, this method provides direct access to the array objects themselves, but this is safe because String is immutable. If the array contained mutable objects, the getItems()
method could return an array of cloned objects instead.
Compliant Solution (Unmodifiable Wrappers)
This compliant solution declares a private
array from which constructs a public immutable list is constructed:from the private array. It is safe to share immutable objects without risk that the recipient can modify them [Mettler 2010].
Code Block | ||
---|---|---|
| ||
private static final String[] items = { ... }; public static final List<String> itemsList = Collections.unmodifiableList(Arrays.asList(items)); |
...
Item 13, "Minimize the Accessibility of Classes and Members" | |
Chapter 6, "Interfaces and Inner Classes" | |
Section 2.2, "Public Fields" | |
Class Properties for Security Review in an Object-Capability Subset of Java |
...
OBJ00-J. Limit the extensibility of classes and methods with invariants