After having covered the Open-Close Principle (OCP), the Liskov Substitution Principle (LSP), the Single Responsibility Principle (SRP) and the Interface Segregation Principle (ISP) let’s talk about the Dependency Inversion Principle (DIP) which is the D in the SOLID acronym. The DIP definition is:

a. High-level modules should not depend on low-level modules. Both should depend on abstractions.

b. Abstractions should not depend on details (concrete implementation). Details should depend on abstractions.

The DIP has been introduced in the 90s by Robert C Martin. Here is the original article.

A Dependency is a Risk

As all SOLID principles DIP is about system maintainability and reusability. Inevitably some parts of the system will evolve and will be modified. We want a design that is resilient to changes. To avoid that a change breaks too much, we must:

first identify parts of the code that are changes-prone.

second avoid dependencies on those changes-prone code portion.

The Liskov Substitution Principle (LSP) and the Interface Segregation Principle (ISP) articles explains that interfaces must be carefully thought out. Both principles are 2 faces of the same coin:

ISP is the client perspective: If an interface is too fat probably the client sees some behaviors it doesn’t care for.

LSP is the implementer perspective: If an interface is too fat probably a class that implements it won’t implement all its behaviors. Some behavior will end up throwing something like a NotSupportedException.

Efforts put in applying ISP and LSP result in interfaces stability. As a consequence these well-designed interfaces are less subject to changes than concrete classes that implement them.

Also having stable interfaces results in improved reusability. I am pretty confident that the interface IDisposable will never change. My classes can safely implement it and this interface is re-used all over the world.

In this context, the DIP states that depending on interfaces is less risky than depending on concrete implementations. DIP is about transforming this code:

static void ClientCode(SqlConnection sqlConnection) { sqlConnection.Open(); } 1 2 3 static void ClientCode ( SqlConnection sqlConnection ) { sqlConnection . Open ( ) ; }

into this code:

static void ClientCode(IDbConnection dbConnection) { dbConnection.Open(); } 1 2 3 static void ClientCode ( IDbConnection dbConnection ) { dbConnection . Open ( ) ; }

DIP is about removing dependencies from high-level code (like the ClientCode() method) to low-level code, low-level code being implementation details like the SqlConnection class. For that we create interfaces like IDbConnection. Then both high-level code and low-level code depend on these interfaces. The key is that SqlConnection is not visible anymore from the ClientCode(). This way the client code won’t be impacted by implementation changes, like when replacing the SQL Server RDBMS implementation with MySql for example.

Let’s underline that this minimal code sample doesn’t do justice to the word Inversion in the DIP acronym. The inversion is about interfaces introduced (to be consumed by high-level code) and implementation details: implementation details depends on the interfaces, not the opposite, here is the inversion.

DIP and Dependency Injection (DI)

The acronym DI is used for Dependency Injection and since it is almost the same as the DIP acronym this provokes confusion. The I is used for Inversion or Injection which might add up confusion. Hopefully DI and DIP are very much related.

DIP states that classes that implement interfaces are not visible to the client code.

DI is about binding classes behind the interfaces consumed by client code.

DI means that some code, external to client code, configures which classes will be used at runtime by the client code. This is simple DI:

static void DICode() { IDbConnection dbConnection = new SqlConnection(); ClientCode(dbConnection); } static void ClientCode(IDbConnection dbConnection) { // Client code has no idea what's behind IDbConnection dbConnection.Open(); } 1 2 3 4 5 6 7 static void DICode ( ) { IDbConnection dbConnection = new SqlConnection ( ) ; ClientCode ( dbConnection ) ; } static void ClientCode ( IDbConnection dbConnection ) { // Client code has no idea what's behind IDbConnection dbConnection . Open ( ) ; }

Many .NET DI frameworks exist to offer flexibility in binding classes behind interfaces. Those frameworks are based on reflection and thus, they offer some kind of magic. The syntax looks like:

// Autofac DI var builder = new ContainerBuilder(); builder.RegisterInstance(new SqlConnection()).As<IDbConnection>(); // UnityContainer DI IUnityContainer container = new UnityContainer(); container.RegisterType<IDbConnection, SqlConnection>(); // NInject DI public class Bindings : NinjectModule { public override void Load() { Bind<IDbConnection>().To<SqlConnection>(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 // Autofac DI var builder = new ContainerBuilder ( ) ; builder . RegisterInstance ( new SqlConnection ( ) ) . As < IDbConnection > ( ) ; // UnityContainer DI IUnityContainer container = new UnityContainer ( ) ; container . RegisterType < IDbConnection , SqlConnection > ( ) ; // NInject DI public class Bindings : NinjectModule { public override void Load ( ) { Bind < IDbConnection > ( ) . To < SqlConnection > ( ) ; } }

And then comes what is called a Service Locator. The client can use the locator to create instances of the concrete type without knowing it. It is like invoking a constructor on an interface:

IDbConnection dbConnection = Locator.Resolve<IDbConnection>(); 1 IDbConnection dbConnection = Locator . Resolve < IDbConnection > ( ) ;

Thus while DIP is about maintainable and reusable design, DI is about flexible design. Both are very much related. Let’s notice that the flexibility obtained from DI is especially useful for testing purposes. Being DIP compliant improves the testability of the code:

class MockConnection : IDbConnection { void Open() { ... } ... } [Test] public void MyTest() { IDbConnection dbConnection = new MockConnection(); // Abstract the test from the database layer var result = ClientCode(dbConnection); Assert.ThingsOn(result); } static Result ClientCode(IDbConnection dbConnection) { dbConnection.Open(); // ... do interesting stuff return result; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class MockConnection : IDbConnection { void Open ( ) { . . . } . . . } [ Test ] public void MyTest ( ) { IDbConnection dbConnection = new MockConnection ( ) ; // Abstract the test from the database layer var result = ClientCode ( dbConnection ) ; Assert . ThingsOn ( result ) ; } static Result ClientCode ( IDbConnection dbConnection ) { dbConnection . Open ( ) ; // ... do interesting stuff return result ; }

DIP and Inversion of Control (IoC)

The Inversion word is used both in DIP and IoC acronyms. This provokes confusion. Remember that the word Inversion in the DIP acronym is about implementation details depending on interfaces, not the opposite. The Inversion word in the IoC acronym is about calls to Library transformed into callbacks from Framework.

IoC is what differentiates a Framework from a Library. A library is typically a collection of functions and classes. On the other hands a framework also offers reusable classes but massively relies on callbacks. For example UI frameworks offers many callback points through graphical events:

class MyForm : FrameworkForm { private Button m_Button = new Button(); public MyForm() { m_Button.OnClick += m_ButtonOnClick; } private void m_ButtonOnClick(Sender sender) { ... } } 1 2 3 4 5 6 7 class MyForm : FrameworkForm { private Button m_Button = new Button ( ) ; public MyForm ( ) { m_Button . OnClick += m_ButtonOnClick ; } private void m_ButtonOnClick ( Sender sender ) { . . . } }

The method m_ButtonOnClick() bound to the Button.OnClick event is a callback method. Instead of client code calling a framework method, the framework is responsible for calling back client code. This is an inversion in the control flow.

We can see that IoC is not related to DIP. However we can see Dependency Injection has a specialization of IoC: DI is an IoC used specifically to manage dependencies.

DIP and the Level metric

Several code metrics can be used to measure, and thus constraint, the usage of DIP. One of these metric is the Level metric. The Level metric is defined as followed:

From this diagram we can infer that:

The Level metric is not defined for components involved in a dependency cycle. As a consequence null values can help tracking component dependency cycles.

The Level metric is defined for any dependency graph. Thus a Level metric can be defined for various granularity: methods, types, namespaces, assemblies.

DIP mostly states that types with Level 0 must be interfaces and enumerations (note that interfaces using others interfaces have a Level value higher than 0). If we say that a component is a group of types (like a namespace or an assembly) the DIP states that components with Level 0 must contain mostly interfaces and enumerations. With a quick code query like this one you can have a glance at types Level and check if most of low level types are interfaces:

from t in JustMyCode.Types where t.Level != null orderby t.Level ascending select new { t, t.Level } 1 2 3 4 from t in JustMyCode . Types where t . Level != null orderby t . Level ascending select new { t , t . Level }

The Level metric can also be used to track classes with high Level values: it is a good indication that some interfaces must be introduced to break the long chain of concrete code calls:

The class Program has a Level of 8 and if we look at the dependency graphs of types used from Program we can certainly see opportunities to introduce abstractions to be more DIP compliant:

DIP and the Abstractness vs. Instability Graph

Robert C. Martin not only coined the DIP but also proposed some code metrics to measure the DIP compliance. See these metrics definitions here. From these metrics an intriguing Abstractness vs. Instability diagram can be plotted. Here we plotted the 3 assemblies of the OSS eShopOnWeb application. This diagram has been obtained from an NDepend report:

The Abstractness metric is normalized : it takes its values in the range [0,1]. It measures the interfaces / classes ratio (1 means the assembly contains only interfaces and enumerations).

The Instability metric is normalized and measures the assembly’s resilience to change. In this context, being stable means that a lot of code depends on you (which is wrong for a concrete class and fine for an interface) and being unstable means the opposite: not much code depends on you (which is fine for a concrete class and wrong for an interface, a poorly used interface is potentially a waste of design efforts).

This diagram shows a balance between the two metrics and defines some green/orange/red zones:

A dot in the red Zone of Pain means that the assembly is mostly concrete and used a lot. This is a pain because all those concrete classes will likely undergo a lot of changes and each change will potentially impact a lot of code. An example of a class living in the Zone of Pain would be the String class. It is massively used but it is concrete: if a change should occur today in the String class the entire world would be impacted. Hopefully we can count on the String implementation to be both performance-wise and bug-free.

A dot in the red Zone of Uselessness means that the assembly contains mostly interfaces and enumerations and is not much used. This makes these abstractions useless.

The Green zone revolves around the Main Sequence line. This line represents the right balance between both metrics. Containing mostly interfaces and being used a lot is fine. Containing mostly classes and not being used much is fine. And then comes all intermediate well balanced values between these 2 extremes represented by the Main Sequence line. The Distance from Main Sequence metric can be normalized and measures this balance. A value close to 0 means that the dot is near the line, in the green zone, and that the DIP is respected.

Conclusion

As the Open-Close Principle (OCP), the Liskov Substitution Principle (LSP) and the Interface Segregation Principle (ISP) the DIP is a key principle to wisely harness the OOP abstraction and polymorphism concepts in order to improve the maintainability, the reusability and the testability of your code. No principle is an island (except maybe the Single Responsibility Principle (SRP)) and they must be applied hands-in-hands.

This article concludes this SOLID posts serie. Being aware of SOLID principles is not enough: they must be kept in mind during every design decision. But they also must be constrained by the KISS principle, Keep It Simple Stupid, because as we explained in the post Are SOLID principles Cargo Cult? it is easy to write entangled code in the name of SOLID principles. Then one can learn from experience. With years, identifying the right abstractions and partitioning properly the business needs in well balanced classes is becoming natural.