views:

38

answers:

1

I have a web application (in ASP.NET MVC) with a Quotations controller. This controller can handle multiple Quotation types, MotorQuotation, PropertyQuotation, etc...

Currently it is using inheritance i.e. a Quotation model and it's children, to model the domain. The various children classes have differences in the data they store and not their behaviors. The difference in behavior would come with their validation methods as the validations can be different dependent on what unique fields a child class may store.

The question is how would someone model the quotation objects using composition instead of inheritance?

+1  A: 

The way you describe the problem, it sounds like this is a good case for using inheritance. The rule of thumb is to use inheritance if A is-a B and to use composition if A is-implemented-in-terms-of B.

The recommendation to prefer composition to inheritance does not mean "never ever use inheritance". It means use inheritance appropriately. For example, if you write a Stack class in C++ using an std::vector, you don't want to derive Stack from vector. A Stack is not a vector, it is implemented-in-terms-of a vector, which implies composition. You also want to avoid creating deep class hierarchies, because that results in tight coupling.

In your case, however, inheritance seems like an obvious choice.

Dima
Exactly. The "prefer composition over inheritance" rule applies specifically to the question of code reuse, not to all aspects of OO design.
Porculus