Prefer composition to inheritance
Skep, after completing the design of its soldiers, who now can conquer the world, you realize one important thing: choosing a has-a relationship rather than inheritance gave more flexibility his plan. Not only has the choice of a family of algorithms easily, but also gave him the opportunity to change at runtime the algorithm to use .
If, as it should be the aim of a design object is the easy reuse and maintainability of the code, the composition definitely wins in the efficiency with respect to inheritance. This concept, or maintainability, it is important also for the fact that during the course of vito software, the stage longer and perhaps harder is definitely the maintenance, which often also involves deep changes to the software created. Giving the ability to dynamically change the software can make maintenance much faster: even the implementation of the methods can remain the same and can only change their call dynamic. Sometimes the
choice between inheritance and composition can be very complicated : In some occasions the two principles may seem absolutely equivalent until we reach a point (applying Murphy usually towards the end of the design of a component) in which one of two behaviors becomes obviously better to use.
In general, during the design, it is good to keep in mind this rule:
Using inheritance as a objects behave like any other, rather than when it seems a subtype .
A case of this example is: Suppose two classes, Rectangle and Square. Obviously, an initial analysis would say that the proper relationship between the two is an is-a relationship in the sense that Square is-a Rectangle, quantp in the square is a special case of the rectangle with the sides all having the same size. But suppose that the class Rectangle abbia ragionevolmente due metodi, setHeight() e setWidth() che ne modificano altezza e larghezza. Square eredita i due metodi ma una volta che vado a chiamarne uno di essi su square evidentemente non succede ciò che volgiamo, rompendo il principio che Square dovrebbe essere un diretto sostituro per Rectangle. Quindi in questo caso l'idea is-a si applica logicamente ma i due oggetti non si comportano allo stesso modo, finendo per dare risultati inattesi.
Comunque sia Skep si ricorda di aver già visto uno schema delle classi come il precedente. Quello finora descritto infatti è il design pattern Strategy , che formalmente può essere descritto così:
Strategy ha lo scopo di definire a family of algorithms, encapsulate it and make them interchangeable. Strategy lets algorithms vary independently from clients and use them.
(Design Patterns, Gamma, Helm, Johnson, Vlissides)
0 comments:
Post a Comment