Immutable Objects in a class hierarchy

I have a project that has data objects that are implemented as beans. These classes form the base of a whole class hierarchy. Reading Joshua Bloch’s book „Effective Java“ I recognised this as a bad architecture. I decided to combine different items from the book: immutable object, builders and components instead of class hierarchy.

If one class in your hierarchy is immutable all subclasses should be as well. If a class is instantiated through a constructor with a builder all subclasses must be instantiated through a builder that is a subclass of the builder of its super class.
So far there is no problem. You end up with two class hierarchies that correspond to each other: The immutable Object class hierarchy and the Builder hierarchy.
Now you want to re factor your class to get rid of this superfluous hierarchy. You make the immutable object a component of the class that originally extended it and delegate all methods. Since the component is immutable it should be final, therefore it must be initialized by the constructor. By design your data model can probably not fully be instantiated at create time. Therefore you change all uses of the model to its mutable helper, the builder. When you reference a value of the object your model might be null and if not it is hard to assert that the model is never null when you call it.
This leads to the reasoning that componentising of immutable objects are a bad idea, especially in respect to class hierarchies.

Schreibe einen Kommentar