Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decoration via constructor injection vs. simple inheritance

Can someone please walk me through the differences between (as in benefits of) creating decorator classes using constructor injection of another class as opposed to class inheritance? In the examples I can think of, I might accomplish the same end goal in one of two ways but I suspect I am missing something fundamental.

like image 955
goldfinger Avatar asked Aug 26 '12 18:08

goldfinger


People also ask

What is difference between inheritance and dependency injection?

One criticism of inheritance is that it tightly couples parent class with child class. It is harder to reuse the code and write unit tests. That's why most developers prefer dependency injection as a way to reuse code. Dependency injection is a way to inject dependencies into a class for use in its methods.

What is dependency injection stack overflow?

Dependency injection is a pattern to allow your application to inject objects on the fly to classes that need them, without forcing those classes to be responsible for those objects. It allows your code to be more loosely coupled, and Entity Framework Core plugs in to this same system of services.


1 Answers

The decorator pattern concerns composing an object. To be able to inherit the type of that object, it must obviously be inheritable. Not all types are designed for inheritance, i.e., meant to be base classes, even if they from a purely technical viewpoint can be inherited (which I consider a design flaw).

The raison d'être for the decorator pattern is to be able to modify the behavior of objects without modifying the objects themselves. By inheriting, you're essentially modifying the object itself and what you get then is regular behavioral change through polymorphism, meaning that you did not accomplish the same thing.

So, both decoration and inheritance has their uses. Use decoration when anyone of these is true

  • you can not inherit (for example if the class is sealed in C#)
  • you should not inherit (the class is obviously not meant to be a base class)
  • you want to change the behavior of one particular object many times (by wrapping it with decorators of different behavior)

Note that inheritance is the most powerful tool there is in the OO toolbox. With great power comes great responsibility and that's not always easy to cope with. I'd say: Always compose or aggregate. When that just cannot be done, inherit. If you can't inherit, try harder to compose or aggregate."

like image 153
Johann Gerell Avatar answered Oct 11 '22 06:10

Johann Gerell