Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This noncompliant code example subclasses the Mutable class with a MutableProtector subclass: 

Code Block
bgColor#ffcccc
langjava
class MutableProtector extends Mutable {
	@Override
    public int[] getArray() {
        return super.getArray().clone();
    }
}
// ...
private Mutable mutable = new MutableProtector();
public Mutable getMutable() {return mutable;} // May be safely invoked by untrusted caller having read ability

In this class, invoking the getter method getArray() does not allow modification of the private internal state of the class, in accordance with OBJ05-J. Defensively copy private mutable class members before returning their references.  HoweverHowever, an untrusted invoker may call the method setArray() and modify the Mutable object..

Compliant Solution

In general, sensitive classes can be transformed into safe-view objects by providing appropriate wrappers for all methods defined by the core interface, including the mutator methods. The wrappers for the mutator methods must throw an UnsupportedOperationException so that clients cannot perform operations that affect the immutability property of the object.

This compliant solution adds a setArray() method that overrides the Mutable.setArray() method and prevents mutation of the Mutable object.:

Code Block
bgColor#ccccff
langjava
class MutableProtector extends Mutable {
	@Override
    public int[] getArray() {
        return super.getArray().clone();
    }
 
	@Override
    public void setArray(int[] i) {
        throw new UnsupportedOperationException();
    }
}

// ...
private Mutable mutable = new MutableProtector();
public Mutable getMutable() {return mutable;} // May be safely invoked by untrusted caller having read ability

...

 

...

Image Modified