Home Architecture Understanding Dependency Inversion Principle with C#

Understanding Dependency Inversion Principle with C#

by Dhanik Lal Sahni

According to Wikipedia the Dependency Inversion Principle (popularized by Robert Martin) states that:

  • High Level Modules should not be depend upon low level modules. Both should depend upon abstractions.
  • Abstraction should not depend upon details. Details should depend upon abstraction.

In application architecture, UI is always on top level. All request goes from UI to business layer and then database layer. Database layer connects with database and fetch required data.
 
When we define Dependency Inversion Principle in above architectute, The presentation layer defines the abstractions it needs to interact with an business layer and the business layer defines the abstractions it needs from a data access layer. The higher layer defines the abstractions and lower layers implement those abstractions.

The second part of the principle stating that abstractions should not depend upon details rather details should depend upon abstractions. It means that if the details change they should not affect the abstraction. Application should keep working as it was working earlier.

Let us take, we have account opening module where notification is sent after opening an account. A printed letter is sent to customer using Notification class.

Here is some model classes for account opening module.

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime DateOfBorth { get; set; }
        public Contact Contact { get; set; }
        public Address Address { get; set; }
    }
    public class Address
    {
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
    }
    public class Contact
    {
        public string Email{ get; set; }
        public string Fax { get; set; }
    }

Notification class which send letter to customer.

    public class Notification
    {
        public Notification()
        {
        }
        public bool SendNotification(Customer customer)
        {
            return Send(customer.Address);
        }
        private bool Send(Address address)
        {
            //Letter Print Logic 
            return true;
        }
    }
    public class Account
    {
        public void OpenAccount()
        {
            Customer customer = new Customer()
            {
                FirstName = "Dhanik",
                LastName = "Sahni",
                DateOfBorth = new DateTime(1981, 07, 05),
                Address = new Address
                {
                    Address1 = "SVF",
                    Address2 = "Lal Kuan",
                    City = "Ghaziabad",
                    State = "UP",
                    Zip = "201002"
                },
                Contact = new Contact
                {
                    Email = "dhanik.sahni@yahoo.com",
                    Fax = "3234234242"
                }
            };
            //concrete  Object 
            Notification notification = new Notification();
            notification.SendNotification(customer);
        }
    }

This code does not have issue at all. Now we have high volume of customer and sending printed letter to each of them is difficult and wast of paper also in some case. Many customer even not opening letter also. So instead of sending printed notification, company decide to send email notification. Now we face problem in our code. Let us problems

  • We have to change code of Account class. As per SRP (Single Responsibility Principle), we should change account class when there will be change required in Account bahaviour. But in case we have to change due to notification, which is wrong.
  • We are using concrete object. We have to change it to abstraction to make code more maintainable. Code should not create object of other dependent object instead that should be passed from caller.
  • There is Interdependence of the modules. Ideally modules should not be interdependent.
  • Changing in existing code may create problem to other parts which is already tested.
  • Account class should not dependent on Notification class. We can overcome this issue by passing object at runtime.

Let us do changes as per DIP principle. We have to create interface for sending notification.

    public interface INotificationSender
    {
        bool SendNotification(Customer customer);
    }

To classes, EmailNotification and LetterNotification is implementing interface INotificationSender. Later on, if any other way of notification is required, we have to simple implement that interface and pass to account class.

    public class EmailNotification : INotificationSender
    {
        public bool SendNotification(Customer customer)
        {
            return Send(customer.Contact);
        }
        private bool Send(Contact contact)
        {
            //Send Email Logic
            return true;
        }
    }
    public class LetterNotification : INotificationSender
    {
        public bool SendNotification(Customer customer)
        {
            return Send(customer.Address);
        }
        private bool Send(Address address)
        {
            //Letter Print Logic 
            return true;
        }
    }

Now we will pass notification object through construction injection to account class.

    public class Account
    {
        INotificationSender emailSender = null;
        public Account(INotificationSender sender)
        {
            //object is passed through constructor
            emailSender = sender;
        }
        public void OpenAccount()
        {
            Customer customer = new Customer()
            {
                FirstName = "Dhanik",
                LastName = "Sahni",
                DateOfBorth = new DateTime(1981, 07, 05),
                Address = new Address
                {
                    Address1 = "SVF",
                    Address2 = "Lal Kuan",
                    City = "Ghaziabad",
                    State = "UP",
                    Zip = "201002"
                },
                Contact = new Contact
                {
                    Email = "dhanik.sahni@yahoo.com",
                    Fax = "3234234242"
                }
            };
            //abstract Object 
            emailSender.SendNotification(customer);
        }
    }

We can pass any notification class at run time. That’s way to create maintainble code.

Summary

Dependency Inversion Principle, give control to pass object to caller object. That help in loosely coupled code. We can change abstraction at runtime based on condition. This also help us in cleaner and managable code.

Complete code sample is available here.

You may also like

Leave a Comment