tags:

views:

243

answers:

2

Do the "Dependency Inversion Principle" (DIP) and "Design to Interfaces Principle" express the same principle? If not, what would be the difference?

EDIT

To clarify and narrow down the context a bit: by interface I mean a programmatic interface, like a Java interface or a pure abstract base class in C++. No other 'contracts' are involved.

A: 

"design by contract" and "dependency injection" are very closely related, but have different levels of abstraction. "design by contract" is a very general design principle, which can be supported by various techniques; In a language that has a Java-like class system, you one technique is to use interfaces to avoid concrete class dependencies. "dependency injection" is another technique, that often relies on the existence of interfaces to function (but need not always do that - It depends on the language). I would say "dependency injection" supports the principle of "design by contract".

troelskn
+3  A: 

Design to interfaces (as a variant of design by contract) supports dependency inversion. Both reduce coupling. However:

  • Design to interfaces and DBC says nothing about how objects are created (e.g. DIP, abstract factories, factory methods).
  • Dependency inversion (dependency injection) generally relies on interfaces, but focuses on the object lifecycle rather than class design. You can use DIP with abstract base classes if you wish, so you aren't really committed to pure interfaces.

The approaches tend to complement each other.

Pontus Gagge
A (pure) abstract base class = interface.
eljenso
And where does the DIP talk about object creation/lifecycles? Maybe some patterns that fall into the "creation" or "lifecycle" category go well with DIP, but surely DIP as a principle doesn't care about that and is all about design.
eljenso