Problem Statement

‘a subclass inherits inappropriate operations from a superclass’

Background

The prime motivation for inheritance and composition in object oriented is code reuse [3]. With inheritance, modifications on the superclass would lead to modifications of the subclass because of the implicit self-recursive re-entrant invocations [1]. Such invocations can hinder the evolution of the model. Object composition depends on message forwarding. This means whenever an object cannot perform a task locally, it seeks assistance from other objects, ideally from ones that are part of it (inner objects), by sending them a message [1]. In object composition, functionality is acquired dynamically at run time. As a result, composition promotes loosely coupled dependencies and flexible code reuse.

Likely causes:

  • Inheritance used where message forwarding would be more appropriate

Possible solutions:

  • Forward messages from an object of the former subclass of an object of the former superclass

Potential risks:

  • Design loses the ability of subclass automatically to inherit new operations added later to superclass
  • Reduced efficiency

Problem Demo

Imagine where you have a simple inheritance (Figure 1), the operation getCountry() returns a string (country name). After new requirements you had to change the superclass to return a new class of type Country, then the FootballTeam subclass will be inheriting invalid operation (“inheritance breaks encapsulation.” [2]). Alternatively, by using composition, as in the Figure 2, the outer class FootballTeam would forward a message to the inner class SportsTeam to execute getCountry() operation, then the FootballTeam would still be able to return a string for its getCountry() operation via getName() public method from Country class.

simple inhertinance
Figure 1 – Simple Inheritance
Composition
Figure 2 – Composition

 

References

  1. Clemens Szyperski. Component Software: Beyond Object-oriented Programming. 2nd edition, 2002
  2. Alan Synder. Encapsulation and inheritance in object-oriented languages. In Object-Oriented Programming Systems, Languages, and Applications Conference Proceedings, pages 38-45, 1986.
  3. Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley, 1995

 

Leave a Reply

Your e-mail address will not be published. Required fields are marked *