Optimizing complex inheritance using traits

In some cases, when the inheritance is complex, the code becomes difficult to maintain. This is the case of multiple inheritance in which each class can inherit from several other classes.

Inheritance facilitates object-oriented design. It allows a child class to use the characteristics of the parent class.

Problematic

In the example below I show you a case of complex inheritance and explain a relevant solution.

Figure 1

In this particular example, imagine that we want to add a method A in classes: class E, class F, class G, class H and class J. But we don’t want to add it in class K. The best solution is to add method A in class B. In this case, class K will inherit method while it does not need it.

Another disadvantage of this architecture is that it becomes more complex over time by adding another inheritance. In this case we can imagine a class L that inherits from the class K, …

Suggestion

The best solution to fix this problem is to break inheritance and put all classes at the same level. This is possible by using traits.

Figure 1 optimized

We can see each class can use several traits.

The class F shares the trait 5 with the classes: class B, class E, class G, class H, class J, class K. But share the trait 4 only with the class G. What is interesting to manage the specificity of each class .

This architecture is better readable and easier to maintain.

Conclusion

When the inheritance is very complex, it is advisable to use traits to facilitate the maintenance of the code.

Leave a Reply

Your email address will not be published. Required fields are marked *