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.
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.
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.
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
sealed
in C#)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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With