The Replace Inheritance with Delegation refactoring (sometimes known as Replace Implementation Inheritance With Composition) provides a systematic way to replace inheritance hierarchies.
Inheritance hierarchies allow system designers to elegantly express relationships between different types of objects in a system. However, such hierarchies can be difficult to implement and refactor. Many developers favour restricting the use of inheritance hierarchies to very simple scenarios. If you started out using inheritance hierarchies (perhaps you had a simple scenario to start with) but are now finding the inheritance hierarchy is now getting in the way, apply this pattern.
Suppose we have the following property-centric class:
We might have a related class such as this:
For this simple case, we can stop here. For more complicated cases, the inheritance might start getting in the way. Here is how you can remove it using traditional delegation:
It looks like we have greatly increased the size of our code. This is because the earlier example was making using of Groovy's compact property notation which we can't use in this case. We should notice however, that most of this code is fairly boiler-plate in style.
Even though this example is not too bad, it becomes annoying to have to read, write and maintain this boiler-plate code. Instead, we can make use of Groovy's Meta-Programming capabilities as follows:
We can run the script as follows:
With the result being: