Deprecated

This guideline has been deprecated.  It has been merged with:

06/15/2015 -- Version 1.0

Similarly, a 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, final Reference)

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 x and 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.

class Point {
  private int x;
  private int y;

  Point(int x, int y) {
    this.x = x;
    this.y = y;
  }
  void set_xy(int x, int y) {
    this.x = x;
    this.y = y;
  }
  void print_xy() {
    System.out.println("the value x is: " + this.x);
    System.out.println("the value y is: " + this.y);
  }
}

public class PointCaller {
  public static void main(String[] args) {
    final Point point = new Point(1, 2);
    point.print_xy();

    // Change the value of x, y
    point.set_xy(5, 6);
    point.print_xy();
  }
}

Compliant Solution (final Fields)

When the values of the x and 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 x and y:

class Point {
  private final int x;
  private final int y;

  Point(int x, int y) {
    this.x = x;
    this.y = y;
  }
  void print_xy() {
    System.out.println("the value x is: " + this.x);
    System.out.println("the value y is: " + this.y);
  }

  // set_xy(int x, int y) no longer possible
}

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:

final public class Point implements Cloneable {
  private int x;
  private int y;

  Point(int x, int y) {
    this.x = x;
    this.y = y;
  }
  void set_xy(int x, int y) {
    this.x = x;
    this.y = y;
  }
  void print_xy() {
    System.out.println("the value x is: "+ this.x);
    System.out.println("the value y is: "+ this.y);
  }
  public Point clone() throws CloneNotSupportedException{
    Point cloned = (Point) super.clone();
    // No need to clone x and y as they are primitives
    return cloned;
  }
}

public class PointCaller {
  public static void main(String[] args) 
      throws CloneNotSupportedException {
    Point point = new Point(1, 2);    // Is not changed in main()
    point.print_xy();
    
    // Get the copy of original object
    Point pointCopy = point.clone();
    // pointCopy now holds a unique reference to the 
    // newly cloned Point instance

    // Change the value of x,y of the copy.
    pointCopy.set_xy(5, 6);

    // Original value remains unchanged
    point.print_xy();
  }
}

The 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.)

The 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.

 

Applicability

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.

Bibliography

[Bloch 2008]

Item 13, "Minimize the Accessibility of Classes and Members"

[Core Java 2004]

Chapter 6, "Interfaces and Inner Classes"

[JLS 2013]

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

 


9 Comments

  1. I'm not that happy with the Point.clone solution. Offering clone() does not relieve calling code from worrying about object references; it merely lets callers copy Point and work with copies leaving the original intact. Safe, but sort of a workaround to the original problem.

    The array NCCE & CS's are interesting, and I think they could use a bit more exploration. I added a code sample where the array is private with a public getter method. Prob need more code examples (both good and bad).

  2. Should we change:

    Consequently, the fields of the referenced object can be mutable.

    To:

    Consequently, the fields of the referenced object are mutable unless they are explicitly declared final.

    ?

    1. I changed it to "may be mutable" and included a quote from the JLS.

  3. This parenthetical comment:

    (unless the unsupported sun.misc.Unsafe class is used)

    raises a lot of questions in my mind which are not answered here.

    1. I replaced it by "by normal Java processing".  Is that better?

  4. This topic's title and content don't seem to quite go together.  the title is very narrow, and a good rule.  however, much of the content seems to be discussing how to protect mutable objects from being accidentally modified.  this is also a good topic.  maybe this rule should be split into 2 rules?

    1. The title and intro are supported very well by the NCCE. I'll agree the CS's are more about "protecting mutable objects", but I don't see how you can rectify the NCCE w/o protecting mutable objects. So I don't think this rule would be better served by being split in two.

      1. That's kind of the problem, you can't recify the NCCE as it stands because the title isn't really a "rectifiable" situation.  how do i "not confuse immutability of a reference with that of the referenced object"?  well, i guess by not confusing them...

        to turn the problem around, say i were writing some code and thinking, "gosh, this object is mutable, but i don't want it to be, how can i rectify that situation?"  if i cracked open this book and looked at the list of rules, i certainly wouldn't read this one first.  i'd probably OBJ57J-G first, and if i didn't want to go the wrapper route, i'd probably end up looking at this one just because it mentions "mutability" (but that would be a last resort).  i certainly wouldn't be expecting to find the solution to the general problem i stated in this article. 

        ultimately, the title of this rule doesn't do justice to the scope of the actual content.

        1. Well, the basic rule is good. Similarly, the CSs are all nicely targeted at how a programmer who was previously confused should fix the situation.

          That said, James's point above is a good one. We may need to fix the title of the rule.  That would be a pity too, though, because the title really seems to nicely encapsulate the confusion we want to address.

          Thoughts, anyone?