Wednesday, August 2, 2017

SOLID Principles - Dependency Inversion Principle

The Dependency Inversion Principle states  "depend upon abstractions, [not] concretions." 

the modules should be depend on the abstract type of module, not actual implemented concrete class and this principle helps to decouple code by ensuring that the class depend on abstractions rather than concrete class. Dependency Injection (DI) is an implementation of this principle

Here is an example to describe the Dependency Inversion Principle

TulipBussiness class, which use the TulipRepository class to get yearly sales of tulip so business class TulipBusiness depends on repository class TulipRepository to get yearly sales.

public class TulipBusiness 
    {

        TulipRepository _repository;


        public TulipBusiness()

        {

            _repository =  new TulipRepository ();
        }    


        public decimal GetTulipSales(int year)

        {

           return _repository.GetYearlySales(year);

        }

    }

as per DI Principle, the class should be depends on abstract instead of concert object, so let refactor above classes.

Let create an abstract type (interface ITulipRepository) for TulipRepository class and modify the TulipBusiness Class and inow TulipBusiness Class will depends on abstract type (Interface ITulipRepository) instead of concreate class TulipRepository and this abstract type is easily being injected into TulipBusiness Class through the Class constructor method.

Here is refactored code

Repository Interface and Class :

    public interface ITulipRepository
    {

        decimal GetTulipSales(int year);

    }


    public interface TulipRepository : ITulipRepository
    {

        public  decimal GetTulipSales(int year)
{}
    }

  

Business Class :

    public interface ITulipBusiness

    {

        decimal GetTulipSales(int year);

    }


    public class TulipBusiness : ITulipBusiness

    {

        ITulipRepository _repository;


        public TulipBusiness(ITulipRepository repository)

        {

            _repository = repository;

        }    


        public decimal GetTulipSales(int year)

        {

           return _repository.GetYearlySales(year);

        }
    }

Benefits of Dependency Injection Principle:
1. Code will be unit testable. we can easily mock the dependency and validate the business logic without calling database or external service call.
2. Class will not be tightly couple with lower-level class
3. Highly reusable code

Other related Links:








Thanks for Visiting!!

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...