Note | ||
---|---|---|
| ||
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.
When you declare a variable final, you do not want anyone to change it. If the type of variable is primitive types, you can undoubtedly make it. Unfortunately, if the variable is a reference to an object, the "final" stuff you think may be not final!
Non-compliant Code Example
In this code, the value of a and b has been changed, which means that when you declare a reference final, it only means that the reference can not be changed but the contents it refer to can still be changed!
Code Block | ||
---|---|---|
| ||
class Test{ Â Â TestPoint { private int x; private int y; Point(int ax, int by) { Â Â this.a this.x = ax; Â Â this.b this.y = by; Â } Â void void set_abxy(int ax, int by) { Â Â this.a this.x = ax; Â Â this.b this.y = by; Â } Â void void print_abxy() { Â Â System System.out.println("the value ax is: " + this.ax); Â Â System System.out.println("the value by is: " + this.by); Â } Â private int a; Â private int b; }} } public class TestFinal1PointCaller { Â Â public public static void main(String[] args) { Â Â Â Â Â Â Â final TestPoint mytestpoint = new TestPoint(1, 2); Â Â Â Â Â Â Â mytestpoint.print_abxy(); Â Â Â Â Â Â Â //now we changeChange the value of ax,b. Â Â Â Â Â Â Â mytest y point.set_abxy(5, 6); Â Â Â Â Â Â Â mytestpoint.print_abxy(); Â Â Â Â Â Â Â Â Â Â } } |
Non-Compliant Code Example
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
:If you do not want to change a and b after they are initialized, the simplest approach is to declare a and b final:_
Code Block | |||
---|---|---|---|
| |||
class Point { private final int x; private final int y; Point(int x  void set_ab(int a, int by) { //But now compiler complains about set_ab method!   this.a = a;   this.b = b;  }  private final int a;  private final int b; |
But now you can not have setter methods of a and b.
Compliant Solution
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:An alternative approach is to provide the clone method in the class. When you want do something about the object, you can use clone method to get a copy of original object. Now, you can do everything to this new object, and the original one will be never changed.
Code Block | ||
---|---|---|
| ||
final public class NewFinalPoint implements Cloneable { private int x; private int y; Point(int x, int y) {  NewFinal this.x = x; this.y = y; } void set_xy(int ax, int by) {   this.a this.x = ax;   this.b this.y = by;  }  void void print_abxy() {   System System.out.println("the value ax is: "+ this.ax);   System System.out.println("the value by is: "+ this.by);  }  void set_ab(int a, int b){   this.a = a;   this.b = b;  }  public NewFinal } public Point clone() throws CloneNotSupportedException{   NewFinal Point cloned = (NewFinalPoint) super.clone();   return cloned;  }  private int a;  private int b; } // No need to clone x and y as they are primitives return cloned; } } public class Test2PointCaller {   public public static void main(String[] args) throws CloneNotSupportedException {        final NewFinalPoint mytestpoint = new NewFinalPoint(1, 2);        mytest // Is not changed in main() point.print_abxy();        //get Get the copy of original object    try {  NewFinal mytest2Point pointCopy = mytestpoint.clone();        //now wepointCopy changenow theholds valuea ofunique a,breference ofto the copy.  // newly  mytest2.set_ab(5, 6);   cloned Point instance //but Change the originalvalue valueof willx,y notof bethe changedcopy.        mytestpointCopy.printset_abxy(5, 6);   } catch (CloneNotSupportedException e) {    // TODOOriginal Auto-generatedvalue catchremains block    e.printStackTraceunchanged point.print_xy();   }  } } |
One common mistake about this is to use public static final array, clients will be able to modify the contents of the array (although they will not be able to change the array itself, as it is final).
Non-compliant Code Example
Code Block | ||
---|---|---|
| ||
 public static final SomeType [] SOMETHINGS = { ... };
|
Wiki Markup |
---|
With this declaration, {{SOMETHINGS\[1\]}}, etc. can be modified by clients of the code. |
Compliant Solution
One approach is to make use of above method: first define a private array and then provide a public method that returns a copy of the array:
Code Block | ||
---|---|---|
| ||
private static final SomeType [] SOMETHINGS = { ... };
public static final SomeType [] somethings() {
 return SOMETHINGS.clone();
}
|
Now, the original array values cannot be modified by a client.
Compliant Solution
An alternative approach is to have a private array from which a public immutable list is contructed:
Code Block | ||
---|---|---|
| ||
private static final SomeType [] THE_THINGS = { ... };
public static final List<SomeType> SOMETHINGS =
 Collections.unmodifiableList(Arrays.asList(THE_THINGS));
|
Now, neither the original array values nor the public list can be modified by a client.
Risk Assessment
Using final to declare the reference to an object is a potential security risk, because the contents of the object can still be changed.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
OBJ03-J | medium | likely | medium | P9 | L2 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
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
Item 13, "Minimize the Accessibility of Classes and Members" | |
Chapter 6, "Interfaces and Inner Classes" | |
[JLS 2013] |
...
Chapter 6, Core Java⢠2 Volume I - Fundamentals, Seventh Edition by Cay S. Horstmann, Gary Cornell
Publisher:Prentice Hall PTR;Pub Date:August 17, 2004