SOLID Principles – Meaning of ‘Depend on Abstractions, Not on Concretions’

design-patternsobject-orientedsolidspring

I was reading SOLID principles on a website, in which for D – Dependency Inversion Principle it says:

“Depend on abstractions, not on concretions”

In other words. we should design our software in such a way that various modules can be separated from each other using an abstract layer to bind them together.

Dependency Inversion Principle Example

The classical use of this principle of bean configuration in the Spring framework.

In spring framework, all modules are provided as separate components which can work together by simply injected dependencies in other module. This dependency is managed externally in XML files.

These separate components are so well closed in their boundaries that we can use them in other software modules apart from spring with same ease. This has been achieved by dependency inversion and open closed principles. All modules expose the only abstraction which is useful in extending the functionality or plug-in in another module.

I have a few questions on it.

  • Depend on abstractions, not on concretions It means, coding to interfaces, not to concrete classes?
  • Why Spring bean example is given? Yes we can use interfaces to inject the dependency. But, we can also inject a concrete class?

Best Answer

Depend on abstractions, not on concretions It means, coding to interfaces, not to concrete classes?

For languages that support interfaces, this is generally the case. But that abstraction layer can be provided via other means, such as an abstract class, a factory, reflection etc. The important thing is that you do not directly couple a requirement to a named, concrete, class.

*Why Spring bean example is given? Yes we can use interfaces to inject the dependency. But, we can also inject a concrete class?

Presumably, because you are looking at "SOLID Principles in Java" (emphasis mine). Spring is a popular DI framework for Java. "But, we can also inject a concrete class?" You always inject a concrete class. But which concrete class is determined by your spring configuration. The receiver of the injection only depends on an abstraction, not that specific class. Having something else tell it what concrete implementation it is to use is the essence of DI.

Related Topic