Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: merged with OBJ50-J

...

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
bgColor#ccccff
private static final String[] items = { ... };

public static final List<String> itemsList =
  Collections.unmodifiableList(Arrays.asList(items));

...

[Bloch 2008]

Item 13, "Minimize the Accessibility of Classes and Members"
Item 14, "In Public Classes, Use Accessor Methods, Not Public Fields"

[Core Java 2004]

Chapter 6, "Interfaces and Inner Classes"

[JLS 20052013]

§4.12.4, "final Variables"
§6.6, "Access Control"

[Long 2005]

Section 2.2, "Public Fields"

[Mettler 2010]

Class Properties for Security Review in an Object-Capability Subset of Java

 

...

OBJ00-J. Limit the extensibility of classes and methods with invariants