Dependency inversion Principle (DIP)

This principle states that the high-level module must not depend on the low-level module, but they should depend on abstractions.

Consider the MessageBoard code snippet below

public class MessageBoard

{

private WhatUpMessage message; public MessageBoard(WhatsUpMessage message)

{

this.message = message;

}

}

The high-level module MessageBoard now depends on the low-level WhatsUpMessage. If we needed to print the underlying message in the high-level module, we would now find ourselves at the mercy of the low-level module. We would have to write WhatsUpMessage specific logic to print that message. If later, FacebookMessage needed to be supported, we would have to modify the high-level module( tightly-coupled code). That violates the Dependency inversion principle.

A way to fix that would be to extract that dependency. Create an interface and add whatever your high-level module needs. Any class that needed to use your high-level module would have to implement that interface.

Your interface would look something like this

public interface IMessage

{

public void PrintMessage();

}

Your MessageBoard now would look like this

public class MessageBoard

{

private IMessage message; public MessageBoard(IMessage message)

{

this.message = message;

} public void PrintMessage()

{

this.message.PrintMessage();

}

}

The low-level module would look like this

public class WhatUpMessage : IMessage

{

public void PrintMessage()

{

//print whatsup message

}

} public class FacebookMessage : IMessage

{

public void PrintMessage()

{

//print facebook message

}

}

That abstraction removes the dependency of the low-level module in your high-level module. The high-level module is now completely independent of any low-level module.

Using the S.O.L.I.D principles when writing code will make you a better developer and make your life a lot easier. You might even become the new popular person on the block if you’re the only one doing it. Thank you for making it to the end. Until next time, Happy coding.