Embrace composition while avoiding inheritance


News: Embrace composition while avoiding inheritance

  1. Junior Java developers think they see inheritance opportunities in every class they build. It seems like a powerful construct, but the reality is that it can be extremely harmful when used improperly. Cameron Laird discusses this fact in his latest article, Against Inheritance: A Better Balance for Object Orientation.


    "One fundamental aspect of OO expressiveness is class definitions in terms of inheritance. Some designers aim for inclusiveness and deep structure; they produce class hierarchies where everything is richly structured in terms of inheritance from carefully constructed base objects.

    "I see a profound mistake in this, if a well-motivated one. Schoolroom exercises simplify real-world situations so that classes have only a few, simple relations to each other. This leads to the habit of thinking that class definitions must have logical relations to each other. Commercial coding deals with far messier situations, where the relationship between WireTransfer and CustomerEvent is ambiguous, at best.  Many times, it’s wisest simply to leave a relationship unbound."

    Read the full article: Against Inheritance: A Better Balance for Object Orientation.

  2. Some remarks:

    • Implementation inheritance is uesful in many cases and not 'dangerous':

        bad: class Car extends Tire

        good: class Car extends AbstractCar


    • Interfaces ("is-a relations") should be developed 'bottom up'. They become obvious only over time and shouldn't be created beforehand.
    • OO is all about behavior, not data. Data is encapsulated if its an implemetation detail or revealed if not. Data structures are not important for OO design.


  3. Oh yes this is how best software developers think







    By the way 


    Welcome to real world, to real software.


  4. Using composition instead of inheritance looks like an escapist solution as it doesn't address the problem, namely the confusion about the semantics of both operators.

    A more rigorous approach would be to distinguish between structural and functional composition or inheritance. On a broader perspective, that would entail two pivotal benefits:

    • It would bring Object and Aspect oriented paradigms under the same modelling roof.
    • It would reinstall the Liskov Principle as the corner-stone of OO modelling by applying it both to internal (aka design) and external (aka analysis) consistency.