This guideline has been deprecated. It has been merged with:
06/15/2015 -- Version 1.0
final method parameter obtains an immutable copy of the object reference. Again, this has no effect on the mutability of the referenced data.
Noncompliant Code Example (Mutable Class,
In this noncompliant code example, the programmer has declared the reference to the
point instance to be
final under the incorrect assumption that doing so prevents modification of the values of the instance fields
y. The values of the instance fields can be changed after their initialization because the
final clause applies only to the reference to the
point instance and not to the referenced object.
Compliant Solution (
When the values of the
y instance variables must remain immutable after their initialization, they should be declared
final. However, this invalidates a
set_xy() method because it can no longer change the values of
With this modification, the values of the instance variables become immutable and consequently match the programmer's intended usage model.
Compliant Solution (Provide Copy Functionality)
If the class must remain mutable, another compliant solution is to provide copy functionality. This compliant solution provides a
clone() method in the class
Point, avoiding the elimination of the setter method:
clone() method returns a copy of the original object that reflects the state of the original object at the moment of cloning. This new object can be used without exposing the original object. Because the caller holds the only reference to the newly cloned instance, the instance fields cannot be changed without the caller's cooperation. This use of the
clone() method allows the class to remain securely mutable. (See OBJ04-J. Provide mutable classes with copy functionality to safely allow passing instances to untrusted code.)
Point class is declared
final to prevent subclasses from overriding the
clone() method. This enables the class to be suitably used without any inadvertent modifications of the original object.
Incorrectly assuming that
final references cause the contents of the referenced object to remain mutable can result in an attacker modifying an object believed to be immutable.
Item 13, "Minimize the Accessibility of Classes and Members"
Chapter 6, "Interfaces and Inner Classes"