Search code examples
design-patternsuser-interfaceinheritancemvpcomposition

Composition vs Inheritance in MVP


I'm using MVP pattern to develop a large scale application. While working in the development I have come up with the question whether if composition or inheritance should be used. For example: Let's assume that I have a form called Foo with fields A and B. In other part of the application I have a form Bar that has the same fields A and B but an additional field C.

Currently, the code is written with the inheritance approach in where the view the form Bar inherits from form Foo. The presenters then handle the data a little different with the model. This works out pretty simply but beats me whether if follows the rule of thumb of "is A" since even when the forms are different they handle common inputs (A and B).

However, here I've been thinking of "composition over inheritance" and the Liskov Substitution Principle and come to think that I should be using composition instead of inheritance. However since I'm using MVP it have been more complicated than expected because I'll have to have a presenter for form Foo with fields A and B then a presenter for Bar with with field C and a reference to the presenter of Foo so that it can inject the fields A and B into it.

The problem is that it it has proven to be more code since I will have to add some sort getters and setters in the presenter of Foo for it to be able to pass the data to Bar. This feels somehow like if I am breaking MVP in order to provide composition.

So my questions are:

Is it really better for my case to use composition over inheritance? Why?

Does using composition "break" MVP?


Solution

  • Is it really better for my case to use composition over inheritance? Why?

    Yes. Because composition is more reliable, more secure, more maintainable, more discoverable, more documentable, and more comprehensible in larger apps. IMHO. :)

    Does using composition "break" MVP?

    Yes. It breaks the kind of simple MVP you're doing now. Composition lets you choose how to couple your code, and this is very good for larger apps. It does use more code because you have to become specific about how you're coupling.

    It is very reasonable for a simple app to grow, and to become a good candidate for a transition from simple MVP inheritance to more sophisticated composition. This is a decoupling step that enables recoupling in new ways.

    This is similar to how many simple web apps are transitioning to become front/back API-driven apps. This is essentially a decoupling of the front-end user views from the back-end storage models.