Showing posts with label SOLID. Show all posts
Showing posts with label SOLID. Show all posts

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!!

SOLID Principles - Interface Segregation Principle

"many client-specific interfaces are better than one general-purpose interface." 

No clients should be forced to implement methods which it does not use and the contracts should be broken down to thin ones

Here is the example to explain the Interface Segregation Principle


Here is an ISystem general purpose interface to perform more than one tasks like print, fax, scan and photocopy.

   interface ISystem

    {

         bool print(Item item);      

         bool fax(Item item);

         bool scan(Item item);

         bool photoCopy(Item item);


    }

but in real world, one system can do only few task example scanner machine can do only scanning similar like Fax machine can do fax only so we need the very granular level of interface for each system.

Here are an example:

For Fax Machine


  interface IFax

    {

         bool Fax(Item Items);

    }


    class FaxMachine : IFax

    {

        public bool Fax(Item Items)

        {

          // Send Fax

        }

    }

  

 For Scanner Machine


 interface IScan

    {

         bool Scan(Item Items);

    }


    class Scanner : IScan

    {

        public bool Scan(Item Items)

        {

            // Scan Letter

        }

    }



In real world, possible one machine can do more than one task, in this scenario we can use inherits more than one interface


interface IXMachine : IScanIFax

    {


    }


    class XMachine : IXMachine

    {

        public bool Fax(Item Items)

        {

            // Send Fax

        }


        public bool Scan(Item Items)

        {

            // Scan Letter

        }

    }


In above code, we have an XMachine which is capable to perform Fax task and also scan task.


Benefits of Interface Segregation Principle:

  • More granular and more specific interface intended to keep a system decoupled and thus easier to refactor, change, and redeploy.
  • Interface should be so smaller and more specific ones so that clients will only have to know about the methods that are of interest to them.  

Other SOLID Principles related Links:







Thanks for Visiting!!

SOLID Principles - Liskov Substitution Principle

The SOLID principles focus on achieving code that is maintainable, robust, and reusable and in this blog, we will discuss the Liskov Substitution Principle.

The derived classes should be perfectly substitutable for their base classes.


Here is an example of Base and derived class:

 Liskov Substitution - Base and Child Class Relation


Rectangle class is base class for Square class and Base class have height, width field and Area function to calculate the area.

public class Rectangle
    {
        public int Height { getprotected set; }
        public int Width  { getprotected set; }

        public virtual void SetWidth(int width)
        {
            Width = width;
        }

        public virtual void SetHeight(int height)
        {
            Height = height;
        }

        public int Area()
        {
            return Width * Height;
        }

    }

    public class Square : Rectangle
    {
        public override void SetHeight(int height)
        {
            Height = height;
            Width = height;
        }

public override void SetWidth(int width)
        {
            Height = width;
            Width = width;
        }

}


Now we will see How the Square Class object will replace the Rectangle base class object, without changing code and can able to calculate the Area of SQUARE by using base class function.

1st example - we instantiate a rectangle object and set height and width of rectangle and call Area () method to get area of rectangle.

Rectangle rect = new Rectangle();
rect.SetHeight(10);
rect.SetWidth(2);
int val = rect.Area(); // Actual value  : 20

2nd example- we are instantiating Square object and assigned to Rectangle object and setting height and width of rectangle and call Area () method to get area of square.

Rectangle rect = new Square();
rect.SetHeight(10);
rect.SetWidth(2);
int val = rect.Area(); // Actual value  : 4


Now in 2nd example, rect holds reference of the type of Square Object, so it’s result is different (area value: 4) and it replace the instance/object of the Rectangle with Square type 

Other Links:


Thanks for Visiting!!

SOLID Principles - Open Closed Principle

In this blog, we will discuss about the open-closed principle and the open-closed principle states

"software application source codes should be open for extension but should be closed for modification."


In different word, the entity’s behavior can be changed without changing the source code.

If module satisfy the open-closed principle that have two benefits.

         Open for extension - means module’s behaviors can be changed
Closed of modification - it is not allowed to change. This can be achieved by using Inheritance


Here is an example to how to implement the open-closed principle by using inheritance in object orient programming

public class Order

    {

        public int OrderID { getprotected set; }

        public string OrderStatus { getprotected set; }

        public DateTime Date { getprotected set; }

        public int CustomerID { getprotected set; }


        ///

        /// This method used to add or update order table

        ///


        /// Order">

        public virtual void Save(Order Order)

        {

        }


        ///



        /// This method used to delete the order record from table

        ///


        /// Order">

        public void Delete(Order Order)

        {

        }      

    }


    public class OrderDetails : Order

    {

        public string Address  { getset; }

        public string City { getset; }

        public string ZipCode { getset; }


        ///



        /// This method used to save details order information

        ///


        /// Order">

        public override void Save(Order Order)

        {


        }

    }


In OrderDetails Class, we are override the behavior Save() method of Base Class

Benefits of Open/Closed Principle:

·         Loose coupling

·         Reduced risk of breaking existing functionality be adding/inheriting new classes



Other Links:








Thanks for Visiting!!


SOLID Principles - Single Responsibility Principle

This blog will discuss about the single responsibility principle and will demonstrates how to implement single responsibility principle in C# with example.

The Letter 'S' of 'SOLID' stands for Single Responsibility Principle and The Single Responsibility Principle (SRP) states

"Every class should have a single responsibility",

In different words that a class should have only one reason to change

A single responsibility should be entirely encapsulated by the class so there should be a single reason for making the change to a class and every behavior/function of class should have just one reason to exist. 
For good quality of code the single responsibility principle is essential.

Here is an example of single responsibility principle:

There is an order class, which perform database crud operation like create, update and delete for order entity and also generate details report for order entity now this order class have two responsibilities:
  1. Update/create/delete order record from table 
  2. Generate detail report for Order.
   public class Order
    {

        public int OrderID { getprotected set; }

        public string OrderStatus { getprotected set; }

        public DateTime Date { getprotected set; }

        public int CustomerID { getprotected set; }
        
        /// This method used to add or update order table        
        public void Save(Order Order)

        {


        }


        /// This method used to update the existing order record
        public void Update(Order Order)
        {


        }


        /// This method used to delete the order record from table

        public void Delete(Order Order)
        {


        }


        /// This method used to generate Order details report
        public string GenerateReport(DateTime start, DateTime End)
        {


        }

    }

This class have 4 methods, first 3 methods have common purpose to maintain (create, update or delete) record in order table but GenerateReport() method have completely different purpose to generate OrderReportData Memory string based on input

As per Single responsibility Principle, there should be two separate classes, one to maintain order record and another to generate order report.
  • Order Class-  update/create/delete order record from table 
  • OrderReport Class – Generate order details report
Here is an Order Class:
public class Order
    {
        public int OrderID { getprotected set; }
        public string OrderStatus { getprotected set; }
        public DateTime Date { getprotected set; }
        public int CustomerID { getprotected set; }
        
        /// This method used to add or update order table        
        public void Save(Order Order)

        {


        }


        /// This method used to update the existing order record
        public void Update(Order Order)
        {


        }


        /// This method used to delete the order record from table

        public void Delete(Order Order)
        {


        }

    }

Here is an OrderReport Class - generate order details report.
 public class OrderReport

    {

        
        /// This method used to generate order details reports       
        public string GenerateOrderReport(Order order)

        {


        }

    }



Other related posts:







Thanks for Visiting!!

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...