Saturday, February 22, 2014

To be Mutable first or to be Immutable first?

Apple's Objective-C library has many pairs of classes like NSDictionary and NSMutableDictionary.  Typically the mutable class inherits from the immutable one to add the write functionality, so that the "normal" class is the immutable one and only in cases where you need to write back to it you declare variables as being mutable.

Apache Commons Configuration has a pair of interfaces Configuration and ImmutableConfiguration. The "normal" Configuration object is the mutable one, and it inherits from ImmutableConfiguration. This is the opposite of Apple's style.

I don't know how many libraries out there even have pairs of classes like this, or whether more of them make mutable normal or immutable normal.  But here's my opinion:

It makes sense for a class or interface X to be immutable, and to have a subclass or subinterface called MutableX which adds the mutable methods.  Given an instance of X, you can check if it is an instance of the mutable subclass or implements the mutable interface.

It makes less sense for a class or interface X to be mutable, and to inherit from a superclass or superinterface called ImmutableX.  This isn't just the opposite of the above because in this case, all instances are either ImmutableX or subclasses or subinterfaces of ImmutableX. So checking to see if an instance is mutable is somewhat strange with this style.

It makes no sense at all  for a class or interface X to be mutable, and to have a subclass or subinterface called ImmutableX which overrides the mutable methods and throws exceptions or does nothing.

In conclusion, make the normal class or interface immutable X first, and subclass or subinterfaces MutableX second. That makes it easy to check whether an instance is mutable or not.

No comments: