Search code examples
oopinheritancecomposition

OOP Reuse without Inheritance: How "real-world" practical is this?


This article describes an approach to OOP I find interesting:

What if objects exist as encapsulations, and the communicate via messages? What if code re-use has nothing to do with inheritance, but uses composition, delegation, even old-fashioned helper objects or any technique the programmer deems fit? The ontology does not go away, but it is decoupled from the implementation.

The idea of reuse without inheritance or dependence to a class hierarchy is what I found most astounding, but how feasible is this?

Examples were given but I can't quite see how I can change my current code to adapt this approach.

So how feasible is this approach? Or is there really not a need for changing code but rather a scenario-based approach where "use only when needed or optimal"?

EDIT: oops, I forgot the link: here it is link


Solution

  • I'm sure you've heard of "always prefer composition over inheritance".

    The basic idea of this premise is multiple objects with different functionalities are put together to create one fully-featured object. This should be preferred over inheriting functionality from disparate objects that have nothing to do with each other.

    The main argument regarding this is contained in the definition of the Liskov Substitution Principle and playfully illustrated by this poster:

    Liskov Substitution Principle: If it looks like a duck, quacks like a duck, but needs batteries - you probably have the wrong abstraction

    If you had a ToyDuck object, which object should you inherit from, from a purely inheritance standpoint? Should you inherit from Duck? No -- most likely you should inherit from Toy.

    Bottomline is you should be using the correct method of abstraction -- whether inheritance or composition -- for your code.

    For your current objects, consider if there are objects that ought to be removed from the inheritance tree and included merely as a property that you can call and invoke.