Mutable, Immutable and Generics

Immutable objects help with avoiding bugs. Suppose I have two interfaces implementing the Immutable Interface pattern. One interface for Point and one with MutablePoint. The pattern suggests a cast to ImmutablePoint p; ((Point)p).setX( 1.0 ); get the mutable interface. This isn't safe and can be replaced with a Generics solution.

First we have the mutable point:

which we want to create from an Immutable object without a cast:

The second benefit beside the missing cast is that users of the Point interface know there is a mutable interface which they can get in a defined way.

The makeMutable() method comes from a generic interface called Mutable

which is extended by the Point interface.

Our Point implementation now only needs to implement MutablePoint and Point. Voila.

A negative side effect is that people who have a reference to a Point object can get a mutable version. When the main point is to have more immutable objects. The other way round is often better, have MutablePoint and create an immutable version.

Thanks for listening.

Update: As pointed out, making an mutable object from an immutable one will break the contract, as will making an immutable one from an mutable one. You do need to copy the object to be safe. For example with a BeanCopier or a copy constructor I've wrote about in Beautiful Java: Reflection and the BeanCopier. Better name the method asMutable than makeMutable

Comments are closed.