DEV Community

Discussion on: OOP is Ruff!

Collapse
 
blackr1234 profile image
blackr1234

Exactly, sometimes has-a is better than is-a, especially for testing.

From GeeksforGeeks "Favoring Composition Over Inheritance In Java With Examples":

Composition offers better test-ability of a class than Inheritance. If one class consists of another class, you can easily construct a Mock Object representing a composed class for the sake of testing. This privilege is not given by inheritance.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

This is generally true because of the way class inheritance is usually implemented in languages, but consider the following example in a made-up language:

class(BaseAnimal) TalkingAnimal extends BaseAnimal {
   define make_sound() { print "I can talk" }
}

// In the actual program:
talking_dog = new TalkingAnimal(Dog)
// When Testing:
talking_dog = new TalkingAnimal(MockDog)
Enter fullscreen mode Exit fullscreen mode

To some extent, this can even be achieved in languages like Ruby, there's just no nice syntax for it.

Thread Thread
 
alrunner4 profile image
Alexander Carter

That's trivial with C++ templates, but the deeper you get into parametric pymorphism, the more you'll realize inheritance is all downside except for the perceived ease of use of not needing to repeat method definitions on superobjects (those with usually a dozen or more low-cohesion methods).

Thread Thread
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

I think the main benefit of inheritance is how object genealogy can make code more self-documenting as well as make it easier for automated tools to draw conclusions about semantics from the code alone.

Whether this is a good trade-off, I can't really comment on, as I've never seen the appeal of class-inheritance based object orientation.