oopdesign-patternsdependency-inversion

Deriving from a concrete class?


In book 'Head First Design Patterns', one of the way mentioned to not violate 'Dependency Inversion' principle is as:

No class derive from a concrete class.

Is it possible to follow this rule thoroughly? In many commonly used frameworks and libraries its common to find classes not following this rule.


Solution

  • Inheritance is an important part of c#, ruling it out would be a waste.

    Nevertheless, the book emphasizes the open for extension closed for change SOLID principle and this is actually a good thing.

    Not to derive from concrete classes ( note, abstract classes and interfaces are not concrete ), helps you to adapt this paradigm. Inheritance is not typically suited for extension, and makes inversion harder ( because the latter relies on interfaces and concretes are not interfaces ).

    So in practice, you'll see that base classes are often abstract. Not all, and not every framework adopts it. Sometimes there are good reasons to inherit from a concrete. But the book, is in it's way a easy read and to go into details on the exceptions would make it much harder to read.

    So bottom line: no, one should not follow the rule at all cost but only do concrete inheritance if one of the following: