I asked this question before but the answer was hand written and I couldn\'t und
ID: 3722772 • Letter: I
Question
I asked this question before but the answer was hand written and I couldn't understand the hand writing so I'm reposting. Question: “Inheritance binds the classes closer together…” This is an example of trading-off increased coupling in exchange for reduced code duplication. Sometimes composition can achieve (perhaps somewhat less) reduction in code duplication while minimizing coupling between classes. Give an example pair of classes with two variations: one using inheritance and one using composition. Discuss the pros and cons.
Explanation / Answer
The merit of inheritance is that Polymorphism will permit us to use a variable of superclass to get a reference of its subclass.
All subclasses of a superclass will maintain "invariant part". And each subclass is supposed to obtain its own "variant part". this will help the code to varry according to situation and makes the maintanence easier.
The main con is that Once a superclass is revised, all the respective subclasses has to be changed.
One example using inheritance is standard geometric figure library. As for 3D geometric figure, they all have some criteria like texture,length etc. But different geometric figure obtain different "invariant part" of parameters, . This "variant part" is subtle and abstract, which can hardly be categorized. Thus, using inheritance in such situation is both convenient and accuracy. The cost is just different parameters of various geometric figures.
now lets discuss about composition
In composition architecture, "Invariant part" lies in a concrete class while "variant part" are realized by back-end object which uses polymorphism mechanism. The pros is that it is easier than inheritance to change code without breaking other part of system. Because it is easier to change a back-end class without breaking the interface of it. However, when implement the same system, composition is often harder to implement and the performance may be compensate by its method-invocation mechanism.
One example using composition structure is describing a character in computer game, such as vicecity. vicecity is a "invariant" character itself, that is, he will not become othercharecter in that game. We can treat action as its back-end class. Action may includes jump, run, swim, fly, climb, fire, etc.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.