Suppose you are working as a
software developer in a company. You have been given a task to
develop a software system design for some real world scenario. One of
the basic activities of any software system design is to establish
relationships between classes. Suppose at the stage of creating relationships
for some classes, you have to choose either inheritance or composition as these
are two fundamental ways to relate classes by achieving feature of code
re-usability. Being a developer, for what reasons, would you prefer one
technique to the other keeping in mind the reusability factor? Support
your answer with solid reasons.
Solution:
Inheritance is not well suited for
code reuse. Inheriting for code reuse usually leads to:
- Classes with inherited methods that must not be called
on them (violating the Liskov substitution principle), which confuses
programmers and leads to bugs.
- Deep hierarchies where it takes inordinate amount of
time to find the method you need when it can be declared anywhere in dozen
or more classes.
Generally the inheritance tree should not get more than two or three levels deep and usually you should only inherit interfaces and abstract base classes.
No comments:
Post a Comment