What methods can be used to use composition over inheritance?

I have a web application (in ASP.NET MVC) with a quote controller. This controller can handle several types of quotes, MotorQuotation, PropertyQuotation, etc.

Currently, it uses inheritance, that is, a quote model, and its children to model the domain. Different classes of children have differences in the data they store, and not on their behavior. The difference in behavior will be related to their validation methods, since validations may differ depending on which unique fields the child classes can store.

The question is, how does someone model quote objects using composition instead of inheritance?

+3
source share
1 answer

As you describe the problem, it seems like this is a good example of using inheritance. A rule of thumb is to use inheritance if A is-a B, and use composition if A is implemented in terms of B.

The recommendation of composition preference for inheritance does not mean "never use inheritance." This means using inheritance appropriately. For example, if you write a class Stackin C ++ using std::vector, you do not want to output Stackfrom vector. A is Stacknot vector, it is implemented in terms vector, which implies composition. You also want to avoid creating a hierarchy of deep classes, as this leads to tight coupling.

, , .

+2

Source: https://habr.com/ru/post/1769901/


All Articles