Dependency Inversion Principle (DIP) – S.O.L.I.D. Framework

Frameworks May 31, 2017

The fifth and final principle within the S.O.L.I.D. Framework is the Dependency Inversion Principle.

The main statement of this principle is “Entities must depend on abstractions not on concretions. It states that the high level module must not depend on the low level module, but they should depend on abstractions”.

On the first sight this may sounds useless, but at the latest when you have to change legacy code – in the following example the database connection – you will love this principle.

In the following example we have an MS SQL connection which violates the Dependency Inversion Principle.

public class SQLDatabase
{
    public void connect()
    {
        string connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["MSSQLConnection"].ConnectionString;
        // Make DB Connection
    }

}

If we are now using this class to connect to the actual database we violate this principle by passing the concrete implement of the SQLDatabase class.

public class Usermanager
{   
    public Usermanager(SQLDatabase database)
    {
        database.connect();
    }
}

Instead of using the concrete ones we should rather introduce interfaces and pass those through. The correct implementation would look like this:

public interface IDatabaseConnection
{
    void connect(string connectionstring);
}
public class SQLDatabase : IDatabaseConnection
{
    public void connect()
    {
        string connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["MSSQLConnection"].ConnectionString;
        // Make DB Connection
    }
}
public class Usermanager
{   
    public Usermanager(IDatabaseConnection database)
    {
        database.connect();
    }
}

Should at some point in the future the Database Connection change or a new Database should be introduced you only have to add a new implementation of the database with the IDatabaseConnection interface. The Usermanger class will not be affected by those changes because this class only depends on the interface itself and not on concrete implementations.

 

 

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.