Pranay Rana: Software Design Patterns
Showing posts with label Software Design Patterns. Show all posts
Showing posts with label Software Design Patterns. Show all posts

Tuesday, May 22, 2018

Factory Design Pattern With Generics

Factory Method design pattern is one of the highly used design pattern, which is used in project to centralize creation of similar family object in application. It's part of creation design patterns as it helps to create objects in application.



Why to Centralize Object creation with Facotry?

  1. To avoid object creation every where in application with New. 
  2. To create object at run-time which serves purpose, based on requirement (i.e. based on input parameters). 
Factory Pattern Implementation

Below is class diagram and code implementation of Factory pattern.

Below code, centralize creation of command objects with help of Factory design pattern. Code below works as below

  • Code below creates different command to perform task such as addemployee, editemployee etc.
  • It's scalable as if developer wants to add new command let's say deleteemployee then it require to create new DeleteEmployee command which inherits from ICommand as other commands do.
  • CommandFactory , its factory pattern base class which has method GetCommand to return requested command based on input string argument. Modification required in GetCommand method when new command need to be added in application.
  • Program is client class which make use of CommandFactory and execute returned command.

    class Program
    {
        static void Main(string[] args)
        {
            ICommand cmd = CommandFactory.GetCommand("AddEmployee");
            Console.WriteLine(cmd.GetType());
            Console.ReadLine();
        }
    }

    public class CommandFactory
    {
        public static ICommand GetCommand(string cmdName)
        {
            if(cmdName=="AddEmployee") 
            {
                return new AddEmployee();
            } 
     else if(cmdName=="EditEmployee") 
            {
                return new EdutEmployee();
            }

            return new NullCommand();
        }
    }

    public class NullCommand : ICommand
    {
        public bool CanExecute()
        {
             Console.WriteLine("Null command");
    return true;
        }

        public void Execute()
        {
           Console.WriteLine("Null command");
        }
    }

    public class AddEmployee : ICommand
    {
        public bool CanExecute()
        {
            //validation
   return true;
        }

        public void Execute()
        {
          //code to execute
        }
    }
 
    public class EditEmployee : ICommand
    {
        public bool CanExecute()
        {
            //validation
             return true;
        }

        public void Execute()
        {
          //code to execute
        }
    }

    public interface ICommand
    {
        bool CanExecute();
        void Execute();
    } 

Following are issues with above code
  1. One big issue with above code is , it's violate Open Close principle. Because whenever new command added in application, developer need to go to Command Factory and need to add if condition for creating it.
    For Example: when there is need of adding Delete command , developer need to open CommandFactory class and need to add if clause for that.
  2. CommandFactory, GetCommand takes string argument to create and return instance of command. If developer pass wrong string argument value it will end up with NullCommand object (which is based on Null object pattern).
    So its not type safe implementation.
  3. CommandFactory, GetCommand can only return ICommand. If developer added new property/method let's say xyz which is specific to command ex. AddEmployee, then developer cannot access it like addCommandObj.xyz as return Command is of type ICommand and it doesnt has that property. 
Generics Based Factory Pattern Implementation

Solution to problem listed above is make use of factory pattern using Generics. Below is diagram and code of implementation


    class Program
    {
        static void Main(string[] args)
        {
            ICommand cmd = CommandFactory.GetCommand<AddEmployee>();
            Console.WriteLine(cmd.GetType());
            AddEmployee addEmployeeCmd = CommandFactory.GetCommand<AddEmployee>();
            Console.WriteLine(addEmployeeCmd.NewEmployeeId);
            Console.ReadLine();
        }
    }

    public class CommandFactory
    {       
        //only create object of type which implement ICommand
        public static T GetCommand<T>() where T:  ICommand
        {
          //it create object using Template type T and by making use of reflection
          //once create factory this way there is no need to open it again for modification
            Type type = typeof(T);
            Object obj = Activator.CreateInstance(type);
            return (T)obj;
        }
    }

    public class EditCommand : ICommand
    {
        public bool CanExecute()
        {
            //validation
            return true;
        }

        public void Execute()
        {
            //code to execute 
        }
    }

    public class AddEmployee : ICommand
    {
        private int newEmployeeId;
        public int NewEmployeeId
        {
            get { return newEmployeeId; }
        }

        public bool CanExecute()
        {
            return true;
        }

        public void Execute()
        {
            //execute code to create employee
            this.newEmployeeId = 1;//created employeeid 
        }
    }

    public interface ICommand
    {
        bool CanExecute();
        void Execute();
    } 

Following are advantages (solutions for previous approach problem) of generics based implementation

  1. It doesn't violate open close principle as object get created using reflection and using Generics Template type T in CommandFacoty class - GetCommand method. Check CommandFacotry Class in above code.
  2. By making use of Generics, it makes CommandFactory strongly type and there is no need string as argument based on which GetCommand method creating object in previous implementation.
     public static T GetCommand<T>() where T:  ICommand 
    if you see signature of GetCommand now,  it force Template type T must implement ICommand interface and so that it only going to create object of types which implement ICommand.
  3. Now factory can return object of specific implemented type like AddEmployee
      AddEmployee addEmployeeCmd = CommandFactory.GetCommand<AddEmployee>();
    
    Above line of code in Program class Main method proves point that now factory can return implemented type that can also be convert to to parent type ICommand.
Wrapping up
Factory pattern is one of the highly used deign pattern which used in most of the application to create and centralize object creation. So when it written not strongly type based way can lead to problem. So it's better to implement it strongly type based way (Generics implementation) to avoid issues and it helps to stick your code with SOLID principle.


Monday, September 7, 2015

Flyweight Design Pattern

The Flyweight Design Pattern is one of the structural patterns introduced by the GOF. The Flyweight Pattern is about creating a pool of objects that allows sharing already existing objects and causing the application to consume less memory.

So this pattern does the following two things because the pattern creates objects once and then saves them to a pool:
  1. Increases application performance in terms of object creation since there is no requirement of creating an object for every request.
  2. Causes the application to consume less memory, since the object already exists in memory and no new object must be created because of the pool.
Ultimately flyweight patterns make the application efficient in terms of memory and processing.

Basic UML class Diagram of Design Pattern

The following image shows the class diagram of the basic Flyweight Design Pattern.



UML class Diagram
  • IFlyweight: Basic contract to be implemented by derived types, in other words by concrete flyweight.
  • FlyweightFactory: It's a factory class used by a client class to get the data from the concreate flyweight. This class is also responsible for creating the pool of an existing object. So when the request for data come that is already requested it returns data from the pool.
  • ConcerateSharedFlyweight1: It's a concreate implementation of the flyweight interface. As the name suggests, an object returned by this class will be shared among the clients of it.
  • ConcerateUnSharedFlyweight1: It's a concreate implementation of the flyweight interface. As the name suggests an object returned by this class will be unshared. That means that every time the client requires a new object.
  • Client: uses the concreate implementation, it creates an instance of Decorate and uses the functionality of it.
Note:UnSharedFlyweight is not always required, it depends on requirements, but SharedFlyweight is always required when you use the flyweight pattern.

The following code is the implementation of the Flyweight Design Pattern and the Class Diagram was shown above.

namespace BasicFlyweightPattern
{
    #region basic implementation
    public class FlyweightFactory 
    {
        public static List<Item> GetStaticItemList(string key)
        {
            IFlyWeight flyWeight = null;
            ICacheManager _objCacheManager = CacheFactory.GetCacheManager();

            if (key == "A")
            {
                if (_objCacheManager.Contains("A"))
                {
                    return _objCacheManager["A"] as List<Item>;
                }
                else
                {
                    flyWeight = new ConcerateSharedFlyweight1();
                }
            }
            else if (key == "B")
            {
                if (_objCacheManager.Contains("B"))
                {
                    return _objCacheManager["B"] as List<Item>;
                }
                else
                {
                    flyWeight = new ConcerateSharedFlyweight2();
                }
            }

            var list = flyWeight.GetList();
            _objCacheManager.Add(key, list);
            return list;
        }
    }

    interface IFlyWeight
    {
        List<Item> GetList();
    }

    public class Item
    {
        public int id { get; set; }
        public string desc { get; set; }
    }

    public class ConcerateSharedFlyweight1 : IFlyWeight
    {
        private List<Item> ItemList;

        public ConcerateSharedFlyweight1()
        {
            ItemList = new List<Item>();
        }

        public List<Item> GetList()
        {
            ItemList.Add(new Item { id = 1, desc = "A1" });
            ItemList.Add(new Item { id = 2, desc = "A2" });
            ItemList.Add(new Item { id = 3, desc = "A3" });
            return ItemList;
        }
    }

    public class ConcerateSharedFlyweight2 : IFlyWeight
    {
        private List<Item> ItemList;

        public ConcerateSharedFlyweight2()
        {
            ItemList = new List<Item>();
        }

        public List<Item> GetList()
        {
            ItemList.Add(new Item { id = 1, desc = "B1" });
            ItemList.Add(new Item { id = 2, desc = "B2" });
            ItemList.Add(new Item { id = 3, desc = "B3" });
            return ItemList;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Item> list =FlyweightFactory.GetStaticItemList("A");
     //List<Item> list = FlyweightFactory.GetStaticItemList("B");            
     foreach (var item in list)
            {
                Console.WriteLine(item.id.ToString() + "  " + item.desc );
           }

            Console.ReadLine();
        }
    }

}
      
The following are points to remember about the preceding code implementation:
  1. The client asks for data from FlyweightFactory by calling GetStaticItemList and passing the key as argument for getting the data.
  2. FlyweightFactory has a static method GetStaticItemList that creates an instance of concrete and gets data if the request is for the first time, for a later request it returns an existing object.
  3. FlyweightFacotry maintains a pool of existing objects using an Enterprise library caching block for sharing data among the clients, in other words different objects.
  4. In the concrete implementation of flyweight, a hardcoded list is returned but in an actual scenario this will be replaced by data from a data source.
  5. Item is a poco class, the list of which is returned from flyweight concrete classes. This class is represented by different items. The following actual scenario provides more detail.
Output



Here the output shows the result of A's same will use the result of B's. If the call comes a second time then the data is retuned from the cache.

Flyweight Design Pattern Example In an Actual Application

Problem Statement

A web application having a dropdown for displaying a list of Country, displaying a list of State, displaying a list of Product and so on in the dropdown and the dropdowns are part of multiple screens that are accessed by multiple users.

In this scenario, to display another kind of list for multiple user requests, the server must connect with the database server multiple times. This reduces the performance of the application and also consumes memory for creating and storing these lists.

Solution

The solution to the preceding problem is to use the Flyweight Design Pattern.

The following is a class diagram of the Flyweight pattern used in the application.


 
Mapping with Basic Implementation.
  • IFlyweightManager is equals to IFlyweight.
  • StaticDataListFlyweightFactory is equal to FlyweightFactory.
  • CountryStaticListManager and ProductStaticListManager is equal to ConcerateSharedFlyweight1 and ConcerateSharedFlyweight2.
  • StaticItem is equal to Item.
namespace FlyWeightPattern
{
    class Program
    {
        static void Main(string[] args)
        {

            List<StaticItem> countrylist = StaticDataListFlyWeidhtFactory.GetStaticItemList("Country");
            foreach (var item in countrylist)
            {
                Console.WriteLine(item.id.ToString() + "  " + item.Code + "  " + item.Description);
            }

            Console.ReadLine();
        }
    }
 public class StaticDataListFlyWeidhtFactory
    {
        public static List<StaticItem> GetStaticItemList(string key)
        {
            IFlyWeightManager manager = null;
            ICacheManager _objCacheManager = CacheFactory.GetCacheManager();

            if (key == "Country")
            {
                if (_objCacheManager.Contains("Country"))
                {
                    return _objCacheManager["Country"] as List<StaticItem>;
                }
                else
                {
                    manager = new CountryStaticListManager();
                }
            }
            else if (key == "ProductType")
            {
                if (_objCacheManager.Contains("ProductType"))
                {
                    return _objCacheManager["ProductType"] as List<StaticItem>;
                }
                else
                {
                    manager = new ProductTypeStaticListManager();
                }
            }

            var list = manager.GetList();
            _objCacheManager.Add(key, list);
            return list;
        }
    }

    interface IFlyWeightManager
    {
        List<StaticItem> GetList();
    }

    public class CountryStaticListManager : IFlyWeightManager
    {
        private List<StaticItem> StaticItemList;

        public CountryStaticListManager()
        {
            StaticItemList = new List<StaticItem>();
        }

        public List<StaticItem> GetList()
        {
            StaticItemList.Add(new StaticItem { id = 1, Code = "IND", Description = "India" });
            StaticItemList.Add(new StaticItem { id = 2, Code = "SRL", Description = "Sri Lanka" });
            StaticItemList.Add(new StaticItem { id = 3, Code = "SA", Description = "South Africa" });
            return StaticItemList;
        }
    }

    public class ProductTypeStaticListManager : IFlyWeightManager
    {
        private List<StaticItem> StaticItemList;

        public ProductTypeStaticListManager()
        {
            StaticItemList = new List<StaticItem>();
        }

        public List<StaticItem> GetList()
        {
            StaticItemList.Add(new StaticItem { id = 1, Code = "0123", Description = "Watch" });
            StaticItemList.Add(new StaticItem { id = 2, Code = "0234", Description = "Shoes" });
            StaticItemList.Add(new StaticItem { id = 3, Code = "0345", Description = "" });
            return StaticItemList;
        }
    }

    public class StaticItem
    {
        public int id { get; set; }
        public string Code { get; set; }
        public string Description { get; set; }
    }
}

Output
 


So the preceding code works the same as already described in the basic implementation of pattern. In the code another type of the list is fetched by passing a different key. For this implementation the keys are Country and Product. In a real application one can have more than this.

The preceding implementation follows the SOLID principle, just one exception is the Factory class that must be modifed when one wants to add a new key so it breaks the rule of single responsibility.

Note: Here the country and product list are hardcoded but in an actual program it is fetched from the database.

Conclusion

This pattern is very helpful in the scenario where one wants to create a pool of objects and share them among the clients (the clients are software programs or classes or web applications as in this example).

Note: This is my point of view regarding patterns. Please provide your feedback regarding it and also provide feedback if something you find is wrong in this.

Monday, July 13, 2015

Open Closed Principle

The Open Closed Principle is one of the SOLID principles defined by Robert C. Martin. The principle says “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification”.

So in simple words it says that an implementation (of a class or function), once created, should be closed for further modification, in other words one should not modify an implementation (of a class or function) of logic and/or functionality. One can do refactoring or resolve errors of implementation (of a class or function) but the implementation (of a class or function) is open for extension, in other words one can extend the implementation (of a class or function) of logic and/or functionality.

Real Life Example of Open Closed Principle

An electric adapter is a good example of this principle.



As you can see in the image:
  1. An adapter in the wall is always closed for modification, in other words we cannot change it once it is fitted or extended if we want more.
  2. But an adapter always provides a method of extension, so we can plug in an extension board of an adapter for more adaptation.
  3. So you plug in an extension board and extend an existing electric adapter fitted in wall.
Example of not following the principle in Application Development

A bank offers various types of the savings accounts (Salary Saving, Regular Saving and so on) that meet the needs of many types of customers. A bank has differing sets of rules and each savings account type has a different set of rules to calculate interest.

To calculate the interest of an account, developers have developed the following class with methods to calculate interest.

Public class SavingAccount   
{   
    //Other method and property and code   
    Public decimal CalculateInterest(AccountType accountType)   
    {   
        If(AccountType==”Regular”)   
        {   
            //Calculate interest for regular saving account based on rules and    
            // regulation of bank   
            Interest = balance * 0.4;   
            If(balance < 1000) interest -= balance * 0.2;   
            If(balance < 50000) interest += amount * 0.4;   
        }   
        else if(AccountType==”Salary”)   
        {   
            //Calculate interest for saving account based on rules and regulation of    
            //bank   
            Interest = balance * 0.5;   
        }   
    }   
}  

So in the preceding code the SavingAccount class's CalculateInterest method does a calcualtion based on the account type like Salary and Regular.

So the implementation is not following the Open Closed principle because if tomorrow the bank introduces a new SavingAccount type then there is a requirement to modify this method for adding a new case for the new account type. An example is if the bank introduces a “Child Savings Account type” requiring a new condition for calculating the interest for this account type. That means that the method is always open for modification.

One more thing to note here is that the method is also not following the Single Responsibility Principle. Since here the method is doing more than one thing, like calculating interest for more than one type.

How to Implement the Open Closed Principle

Inheritance is only one way to implement the Open Closed Principle. Because inheritance is only an Object Oriented Design (OOD) basic pillar that allows extension of functionality of an existing class.

To implement the Open Closed Principle one can use interface, an abstract class, abstract methods and virtual methods than inherit them when you want to extend functionality.

So the preceding problem of a Savings Account can be resolved as in the following.


 
Interface ISavingAccount   
{   
   //Other method and property and code   
   decimal CalculateInterest();   
}   
Public Class RegularSavingAccount : ISavingAccount   
{   
  //Other method and property and code related to Regular Saving account   
  Public decimal CalculateInterest()   
  {   
    //Calculate interest for regular saving account based on rules and    
    // regulation of bank   
    Interest = balance * 0.4;   
    If(balance < 1000) interest -= balance * 0.2;   
    If(balance < 50000) interest += amount * 0.4;   
  }   
}   
   
Public Class SalarySavingAccount : ISavingAccount   
{   
  //Other method and property and code related to Salary Saving account`   
  Public decimal CalculateInterest()   
  {   
    //Calculate interest for saving account based on rules and regulation of    
    //bank   
    Interest = balance * 0.5;   
  }   
}  

In the preceding code two new classes are created, RgularSavingAccount and SalarySavingAccount, that is inherited from IsavingAccount.

So if there is a new account added by the bank than there is no need to modify the logic of exiting classes, just extend the functionality by inheriting an interface.

Finally the preceding example implements the Open Closed Principle since there is no need to modify the existing implemented logic and it allows extension for adding new logic.

And the preceding example also implements the Single Responsibility Principle since each class or function is doing only one task.

Note : An interface is created here just as an example. There could be an abstract class of SavingAccount that is implemented by a new savings account type.

Read: Decorate design pattern that also helps to understand.

Disadvantage of not following Open Closed Principle
  1. Since a class or function always allows the addition of new logic, whenever new logic is added it is always necessary to test for full functionality. That requires the addition of a new test case for the added functionality and might also require the modification of an existing test case that fails because of added functionality.
  2. It also breaks the Single Responsibility Principle since a class or function might end up doing multiple tasks.
  3. Class or function maintenance becomes difficult since a class or function can become thousands of lines of code that is difficult to understand.
How to Identify not following Single Responsibility Principle

A class or function is always open for modification, in other words always allows adding more logic to it. Like in the preceding example.

Monday, April 20, 2015

Single Responsibility Principle In Detail

Single Responsibility Principle – is one of the SOLID principles defined by Rober.C.Martin. Principle says “Implementation (Class/ Function) should perform only one task or Implementation (Class/Function) should change for only one reason”.

So in simple word it says “Whatever developer implements (Class/Function) in code during development should perform only one task and developer should only have one reason to change implementation (Class/Function).”

Wrong interpretation of the Principle:


Most of developer interprets it as “Class should perform only one task”. But it’s not only class, function you implement in code during development should also need to perform only one task. So one should interpret it as “Implementation(Class/Function) should perform only one task”

Real Life Example of not following Single Responsibility Principle


What happens when one can do more than one tasks. Below is image example of it



One can able to perform multiple tasks there is no question in it, but it’s not going to provide quality /better output. So to get good quality/better output of work, one should do one task at time.

Example of not following Principle in Application Development


In programming i.e. during developing code as below Order class not following principle

Public class OrderManager
{
 Public List<string> ValidateOrder()
 {
  //Code for validation
 }

 Public bool SaveOrder(OrderInfo order)
 {
  //Code for saving order
 } 

 Public void NotifyCustomer()
 {
  //Code for notification 
 }
}

Above order class having following responsibility
  1. ValidateOrder - Validating Order placed by customer and return error message if any
  2. SaveOrder – Saving Order placed by Customer and return true/false
  3. NotifyCustomer – Notify customer order is placed 

Method not following principle


Public int SumOfAllCustomerOrder(int customerId)
{
            int sum =0;
  var query= “Select * from order where customerid =” + customerid;;
           //query orders
          foreach(Order in OrderCollection)
          {
  If(Order.Items.Count > 5)
             Sum += Order.Price;            
          } 
  return sum;
}

Above method having following responsibility
  1. Method first all the order
  2. It went through all order in collection and do some of that 

Following Single Responsibility Principle


To make class or function to following Single Responsibility Principle, divide responsibility by creating new classes or function

Public Class OrderValidator
{
   Public List<string> Validate(Order order) { //code for validation}
}

Public Class Notifier
{
   Public void Notify(string emailId) { //code for notification}
}

Public Class OrderManager
{
  Private readonly OrderValidator orderValidator;
  Private readonly Notifier notifier;
  Public OrderManager(OrderValidator oValidator, Notifier nFier)
  {
 orderValidator = oValidator;
   notifier = nFier;
  }

   Public bool SaveOrder(OrderInfo orderInfo) 
  { 
     //Validate order 
  orderValidator.Validate(orderInfo);
        //code for saving order //this might be call to repository to save order 
        //notify after successful saving
        notifier.Notify(orderInfo.EmailId)
  }

   Public List<orderinfo> GetOrders(int customerId) { //code for getting order by cusotmerid}
}

Above code shows the three classes which is having only single responsibility to perform.

For method it will be like

Public List<orderinfo> GetOrder(int customerId)
{
            int sum =0;
  var query= “Select * from order where customerid =” + customerid;;
           //query orders
          return ordercollection;
}

Public int SumOfAllCustomerOrder(int customerId)
{
          var OrderCollection = GetOrder(customerId);
          foreach(Order in OrderCollection)
          {
  If(Order.Items.Count > 5)
             Sum += Order.Price;            
          } 
  return sum;
}

Note:

Following Single Responsibility doesn’t mean one can create class with one method.

Disadvantage of not following Single Responsibility Principle


In programming if developer write a class/function that performs more than one task always cause problem in providing good quality. Following problems related to class perform more than one task
  1. It’s very difficult for the other developer (i.e. who is not having any knowledge of class) to understand class/function.
  2. It’s difficult for the other developer to maintain the class/function or change the class/function.
  3. Writing test cases for the class/function also becomes difficult. 

How to Identify not following Single Responsibility Principle


  1. Try to write one line description of the class or method, if description contains word like (and, or, but, if). Example description of the class listed above where not following single resposiblity is: 
  2. “Order class that performs order saving, notification to customer and validate order”.
  3. Class constructor taking more than three argument or Method contains too many parameters.
  4. Class or Method is too long implementation.
  5. Class is low cohesive. Read more about cohesion : http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29


Ref. From: Clean code – Robert .C. Martin

Sunday, February 1, 2015

How and Where Decorator Design Pattern

Decorator Design Pattern

Decorator design pattern is one of the behaviour pattern introduced by GOF. Decorator design pattern is used during development to provide extra functionality to existing Types. So Decorator Design pattern allow developer to achieve rule of SOLID rules
  1. Single Responsibility Principle – Class/Function should do only one task or Class/ Function should have only one reason to change. 
  2. Open Close Principle – Class/Function open for extension but close for modification.
  3. Liskov Substitution type – If type S is derived from Type T than , object of Type T can replace object of Type S.
Decorator means decor basic element to achieve extra functionality. Below image is one of the presentations of decoration


Image shows gift with the basic box and other image is decoration on gift with good wrapping. Extra functionality achieved over here is good look on the basic gift with the help of wrapping decoration.

Simple Example of Design Pattern

Below image shows the class diagram of basic decorator design pattern



  • IBasicService - Basic contract that need to be implemented by derived types.
  • BasicServiceImplementation – Its basic/concreate implementation which is derived from interface, as it basic its provides basic functionality.
  • Decorator1OnBasic & Decorator2OnBasic – its decorated implementation which is derived from interface. It’s actually providing extra functionality over basic implementation.
  • Client – make use of the concreate implementation, it creates instance of Decorate and use functionality of it. Code below is implementation of the Decorator design pattern and Class diagram discussed above.
namespace BasicDecoratorPattern
{
    public interface IBaseService
    {
        void Print();
    }

    public class BasicServiceImplementaion : IBaseService
    {
        public void Print()
        {
            Console.WriteLine("Basic Item");
        }
    }

    public class Decorator1OnBasic : IBaseService
    {
        private readonly IBaseService BasicRealTimeService;
        public Decorator1OnBasic(IBaseService service)
        {
            BasicRealTimeService = service;
        }

        public void Print()
        {
            BasicRealTimeService.Print();
            Console.WriteLine("Extra functionality from Decorator ONE");
        }
    }

    public class Decorator2OnBasic : IBaseService
    {
        private readonly IBaseService BasicRealTimeService;
        public Decorator2OnBasic(IBaseService service)
        {
            BasicRealTimeService = service;
        }

        public void Print()
        {
            BasicRealTimeService.Print();
            Console.WriteLine("Extra functionality from Decorator SECOND");
        }
    }

    public class Client
    {
        public Client()
        {
            IBaseService realTimeService = new BasicServiceImplementaion();

            IBaseService basicRealTimeServiceDecorator1 = new Decorator1OnBasic(realTimeService);
            IBaseService basicRealTimeServiceDecorator2 = new Decorator2OnBasic(realTimeService);

            basicRealTimeServiceDecorator1.Print();
            basicRealTimeServiceDecorator2.Print();
        }
    }
}

Points to remember in above code implementation
  1. DecoratorOnBaisc take IBasicService instance as input to create instance of decorator class.
  2. Client create instance of BasicServiceImplementation first and pass that instance to the decorator.
  3. Decorator make use of the basic implementation instance passed as argument to it to achieve basic functionality and extra functionality by decorating it.
Output
Output shows that decorator add extra functionality over the basic functionality. To understand more below is one more example of decorator pattern in real world.

Real-World Example of Design Pattern

Below is class diagram of Real-World design pattern, Below class diagram represent different kind i.e. different kind of the Milkshake (Mango & Chocolate) over basic Milkshake.


Mapping with Basic Implementation
  • IMilkShake is equals to IBasicService
  • MilkShake is equeal to BasicImplementation.
  • MangoMilshake & ChoclateMilkShake is equal to Decorator1OnBasic & Decorator2OnBasic.
Note in this implementation MilshakeDecorator is abastract class which is derived from the IMilkShake and Decorator of the MilkShake is derived from this decorator class. There are some common functionality so this class is created but it doesn’t affect actual implementation of Decorator pattern.

namespace RealWorldDecoratorPattern
{
    public interface IMilkShake
    {
        string Serve();
        int Price();
    }

    public class MilkShake : IMilkShake
    {
        public string Serve()
        {
            return "MilkShake";
        }

        public int Price()
        {
            return 30;
        }
    }

    public abstract class MilkshakeDecorator : IMilkShake
    {
        public readonly IMilkShake Milkshake;
        public MilkshakeDecorator(IMilkShake milkShake)
        {
            Milkshake = milkShake;
        }
        public string Flavour { get; set; }
        public int FlavourPrice { get; set; }

        public abstract string Serve();
        public abstract int Price();

    }

    public class MangoMilkShake : MilkshakeDecorator
    {
        public MangoMilkShake(IMilkShake milkShake)
            : base(milkShake)
        {
            this.Flavour = "Mango";
            this.FlavourPrice = 10; 
        }

        public override string Serve()
        {
            return  "Serving " + this.Flavour + " " + Milkshake.Serve();
        }

        public override int Price()
        {
            return  this.FlavourPrice  + Milkshake.Price();
        }
    }

    public class ChoclateMilkShake : MilkshakeDecorator
    {
        public ChoclateMilkShake(IMilkShake milkShake)
            : base(milkShake)
        {
            this.Flavour = "Choclate";
            this.FlavourPrice = 20;
        }

        public override string Serve()
        {
            return "Serving "  + this.Flavour + " " + Milkshake.Serve();
        }

        public override int Price()
        {
            return this.FlavourPrice + Milkshake.Price();
        }
    }

    public class Client
    {
        public Client()
        {
            IMilkShake milkShake = new MilkShake();

            IMilkShake mangoMilkshake = new MangoMilkShake(milkShake);
            IMilkShake choclateMilkshake = new ChoclateMilkShake(milkShake);

            Console.WriteLine(mangoMilkshake.Serve());
            Console.WriteLine(mangoMilkshake.Price());

            Console.WriteLine();

            Console.WriteLine(choclateMilkshake.Serve());
            Console.WriteLine(choclateMilkshake.Price());
        }
    }

}

Output

In above code MilkShake Decorator class (Mango and Chocolate) make use of bas Mikshake class. Decorator class provide decoration on the Basic Milkshake class and provide output by using basic implement and extra functionality.

Use of Design Pattern in Application

Above two example helps to understand Decorator design pattern Basic and RealWorld problem. But in this section is help you to understand how to user Design pattern in Application i.e. where developer can possibly use it in Application.

Decorator design pattern it very helpful to achieve cross cutting concern/Aspect oriented programming concepts like
  1. Authentication
  2. Authorization
  3. Logging
  4. Caching
  5. Validation
  6. Exception Management
Apart from Cross cutting concern as explain before it can be used to decorate class with extra added functionality i.e. it not always true that you can use decorator pattern just to achieve cross cutting concern.

Below is Class diagram of the achieving Caching Cross Cutting Concern with the CachingDecorator.

  • IProvides is equal to IBasicService – for this example its contract which is having GetProviderList.
  • Provider is equal to BasicServiceImplementation – for this example is concrete implementation and used to get list of providers.
  • CacheProvider is equal to DecoratorOnBasic – for this example this is decorator which does task of caching fetched providers and when requested it provide cache data or if cache data is not available than it request fresh data from Provider (basic) implementation.
namespace CacheDecoratorPattern
{
    public interface IProviders
    {
        NameValueCollection GetProviderList();
    }

    public class Providers : IProviders
    {
        public NameValueCollection GetProviderList()
        {
            NameValueCollection providerList = new NameValueCollection();
            providerList.Add("SQL", "SQLProvider");
            providerList.Add("Oracle", "OracleProvider");
            providerList.Add("MySQL", "MyProvider");
            return providerList;
        }
    }

    public class CacheProvider : IProviders
    {
        private readonly IProviders provider;

        private NameValueCollection CachedProviderList;

        public CacheProvider(IProviders provider)
        {
            this.provider = provider;
        }

        public NameValueCollection GetProviderList()
        {
            if(CachedProviderList == null)
                CachedProviderList = provider.GetProviderList();

            return CachedProviderList;
        }
    }

    public class Client
    {
        public Client()
        {
            IProviders provider = new Providers();
            CacheProvider cacheProvider = new CacheProvider(provider);

            var providerlist = cacheProvider.GetProviderList();
        }
    }
}

In code CachProvider is class which is decorator over Provider class and take IProvider as input to it. As it just example right now cache value stored in private variable of CacheProvider but in real application this can be replace by real caching i.e. it can be web application cache class or Enterprise application library cache block.

Decorator with Dependency injection Container

Below is just example code to register decorator instance with the Microsoft Unity container Register Decorator

var container = new UnityContainer();
  container.RegisterType(
      typeof( IProvider ),
      typeof( Provider ),
      "BasicProvider"
  );
  contract.RegisterType(
      typeof( IProvider ),
      typeof( CacheProvider ),
     new InjectionConstructor(
         new ResolvedParameter(
             typeof( IProvider ),
             "BasicProvider"
         )
     )
 );

So once it gets register, with Resolve method of container one can easily get instance of the Decorator.

var contract = container.Resolve<IProvider>();

At the End Achieved SOLID principle

Single Responsibility Principle – As in the example Basic implementation Provider does task which it is responsible for example – fetching data in last example. And the decorator is responsible for doing extra functionality like CacheProvider does task for caching data not task of getting data.

Open Close Principle - As rule states here Basic implementation Provider is close for the modification but open for extension that achieved through CachProvider which extends functionality of basic implementation.

Liksov Subtitution Principle – As rule sates here Basic implementation Provider object replaced by the parent type IProvider interface in Decorator constructor where Provider object injected by client class.

Note:
This is my point of view regarding pattern. Please provide your feedback regarding it and also provide feedback it something you find wrong in this.

Sunday, January 18, 2015

Publisher/Subscriber pattern with Event/Delegate and EventAggregator

Publisher/Subscriber pattern

Publisher/Subscriber pattern is one of the variations of the Observer designer pattern introduced by GOF in software development. In Publisher/Subscriber pattern publisher (entry responsible for publishing message) publish message and there are one or more Subscriber (entity who subscribe (i.e. interested in message) to particular message type)  who capture published message. Below image describe the scenario of publisher and subscriber pattern where Publisher publish two type of message (MessageA and MessageB) and Subscribers of the message receive the message in which they subscribed (Subscriber1 capture MessageA and Subscriber2 & Subscriber3 capture MessageB).


To understand this consider Real life senario where Mobile operators sending message to their customers.

As in above image Mobile operator publisher(broadcast) message (Message of Cricket Score and Message of Latest News) and message capture by the customer cells who subscribed for the message(Customer1 & Customer2 capture cricket score message and Customer3 & Customer4 capture latest news message).

Implementation with Event

Oneway to achieve Publisher/Subscriber pattern in application is make use of Event/Delegate i.e. with the help of framework. Below is detail description of publisher/subscriber implementation

Message - Below is class which represent message that is publish by Publisher and capture by interested Subscriber.

public class MessageArgument<T> : EventArgs
    {
        public T Message { get;  private set; }
        public MessageArgument(T message)
        {
            Message = message;
        }
    }
In technical term MessageArgument is generic class so instance of this class can be of any type which is represent by T template type.

Publisher  - as already described above in definition, Publisher is responsible for publish message of diffrent types.
 public interface IPublisher<T>
    {
        event EventHandler<MessageArgument<T>> DataPublisher;
        //void OnDataPublisher(MessageArgument<T> args);
        void PublishData(T data);
    }

    public class Publisher<T> : IPublisher<T>
    {
        //Defined datapublisher event
        public event EventHandler<MessageArgument<T>> DataPublisher;

        private void OnDataPublisher(MessageArgument<T> args)
        {
            var handler = DataPublisher;
            if (handler != null)
                handler(this, args);
        }


        public void PublishData(T data)
        {
            MessageArgument<T> message = (MessageArgument<T>)Activator.CreateInstance(typeof(MessageArgument<T>), new object[] { data });
            OnDataPublisher(message);
        }
    }
Technically Publisher is generic class which inherit IPublisher interface, as Publisher is generic class instance of it can be of any type which is represented by T template type. Publisher Instance of created of selected given type publish on that type of message only. For publishing different type message it requires to create  different type of Publisher Instance. To understand better read below how to use publisher in client class code.

Publisher Class provide event DataPublisher , subscriber attach themselves to this event to listen the message.

PublishDta is publisher class method that publish data to Subscribers.

Subscriber - Subscriber captures message of the type it interested in.
 public class Subscriber<T>
    {
        public IPublisher<T> Publisher { get; private set; }
        public Subscriber(IPublisher<T> publisher)
        {
            Publisher = publisher;
        }
    }

Technically Subscriber is generic class allows to create multiple instance of subscriber and each subscriber subscribe to message it interested in using publisher.

Subscriber pass instance of particular type publisher to capture message publisher by that Publisher.

How it works
 public class Client
    {
        private readonly IPublisher<int> IntPublisher;
        private readonly Subscriber<int> IntSublisher1;
        private readonly Subscriber<int> IntSublisher2;

        public Client()
        {
            IntPublisher = new Publisher<int>();//create publisher of type integer

            IntSublisher1 = new Subscriber<int>(IntPublisher);//subscriber 1 subscribe to integer publisher
            IntSublisher1.Publisher.DataPublisher += publisher_DataPublisher1;//event method to listen publish data

            IntSublisher2 = new Subscriber<int>(IntPublisher);//subscriber 2 subscribe to interger publisher
            IntSublisher2.Publisher.DataPublisher += publisher_DataPublisher2;//event method to listen publish data

            IntPublisher.PublishData(10); // publisher publish message
        }

        void publisher_DataPublisher1(object sender, MessageArgument<int> e)
        {
            Console.WriteLine("Subscriber 1 : " + e.Message);
        }

        void publisher_DataPublisher2(object sender, MessageArgument<int> e)
        {
            Console.WriteLine("Subscriber 2 : " + e.Message);
        }
    }
As you can see in the above code Client is class which create publisher and subscriber. Client class creates Publisher of integer type (in practice you can create any time of publisher) and creates two Subscriber classes which subscribe to the publisher message by attaching DataPublisher event which is provide by Publisher class.

So when you care instance of Client class you will receive following output



So as per the output Publisher of integer type published message "10" and two Subscriber who subscribed to publisher capture and displays message to output.

In practical scenario i.e. in actual application, one need to create all publisher at application start point i.e. at entrypoint of app and pass instance of publisher when creating subscriber.

For Example in Windows application create publisher in Main() Method , in Web Application create publisher in Appication_Start method of Global.asax or make use of Dependency Injection in which you register your publisher and use container to create when needed.
Once created you can pass the publisher in Subscriber as done in above client class code.

Implementation with EventAggregator

EventAggregator - by name one can easily say that it aggregate events. In Publisher/Subscriber EventAggregator is woks as HUB whose task is to aggregate all publish message and send message to interested subscribers.

As you can see in above image EventAggregator comes as HUB between publisher and Subscriber, it works like this
  1. Publisher publish message
  2. EventAggregator Receives message send by publishers
  3. EventAggregator get list of all subscriber interested message
  4. EventAgregator sends message to interested subscriber
EventAggregator Implementation

Subscription - It class which used to create subscription token. When Subscriber subscribe to interested message type via EventAggregator return Subscription token which further used by Subscriber to keep track of its subscription.

 //Does used by EventAggregator to reserve subscription
    public class Subscription<Tmessage> : IDisposable
    {
        public readonly MethodInfo MethodInfo;
        private readonly EventAggregator EventAggregator;
        public readonly WeakReference TargetObjet;
        public readonly bool IsStatic;

        private bool isDisposed;
        public Subscription(Action<Tmessage> action, EventAggregator eventAggregator)
        {
            MethodInfo = action.Method;
            if (action.Target == null)
                IsStatic = true;
            TargetObjet = new WeakReference(action.Target);
            EventAggregator = eventAggregator;
        }

        ~Subscription()
        {
            if (!isDisposed)
                Dispose();
        }

        public void Dispose()
        {
            EventAggregator.UnSbscribe(this);
            isDisposed = true;
        }

        public Action<Tmessage> CreatAction()
        {
            if (TargetObjet.Target!=null && TargetObjet.IsAlive )
                return (Action<Tmessage>)Delegate.CreateDelegate(typeof(Action<Tmessage>), TargetObjet.Target, MethodInfo);
            if(this.IsStatic)
                return (Action<Tmessage>)Delegate.CreateDelegate(typeof(Action<Tmessage>), MethodInfo);

            return null;
        }
    }
EventAggregator -

public class EventAggregator
    {
        private readonly object lockObj = new object();
        private Dictionary<Type, IList> subscriber;

        public EventAggregator()
        {
            subscriber = new Dictionary<Type, IList>();
        }

        public void Publish<TMessageType>(TMessageType message)
        {
            Type t = typeof(TMessageType);
            IList sublst;
            if (subscriber.ContainsKey(t))
            {
                lock (lockObj)
                {
                    sublst = new List<Subscription<TMessageType>>(subscriber[t].Cast<Subscription<TMessageType>>());
                }

                foreach (Subscription<TMessageType> sub in sublst)
                {
                    var action = sub.CreatAction();
                    if (action != null)
                        action(message);
                }
            }
        }

        public Subscription<TMessageType> Subscribe<TMessageType>(Action<TMessageType> action)
        {
            Type t = typeof(TMessageType);
            IList actionlst;
            var actiondetail = new Subscription<TMessageType>(action, this);

            lock (lockObj)
            {
                if (!subscriber.TryGetValue(t, out actionlst))
                {
                    actionlst = new List<Subscription<TMessageType>>();
                    actionlst.Add(actiondetail);
                    subscriber.Add(t, actionlst);
                }
                else
                {
                    actionlst.Add(actiondetail);
                }
            }

            return actiondetail;
        }

        public void UnSbscribe<TMessageType>(Subscription<TMessageType> subscription)
        {
            Type t = typeof(TMessageType);
            if (subscriber.ContainsKey(t))
            {
                lock (lockObj)
                {
                    subscriber[t].Remove(subscription);
                }
                subscription = null;
            }
        }

    }
In above code
Dictionary<Type, IList> subscriber - is dictionary in which Type is Type of message and IList is list of action. So it holds list of action mapped to particular Message Type.

public void Publish<TMessageType>(TMessageType message) - is method used to publishing message. As in code this method does receives message as input than it filter out list of all subscriber by message type and publish message to Subscriber.

public Subscription<TMessageType> Subscribe<TMessageType>(Action<TMessageType> action) - is method used to subscribe interested message type. As in code this method receives Action delegate as input. It maps Action to particular MessageType, i.e. it create entry for message type if not present in dictionary and maps Subscription object  (which waps Action) to message entry.

public void UnSbscribe<TMessageType>(Subscription<TMessageType> subscription) - is method used to unsubscribe form particular message type. It receives Subscription object as input and remove object from the dictionary.

How To Use

      static void Main(string[] args)
        {
            EventAggregator eve = new EventAggregator();
            Publisher pub = new Publisher(eve);
            Subscriber sub = new Subscriber(eve);

            pub.PublishMessage();

            Console.ReadLine();

        }

As in above code shows it first create instance of EventAggregator which pass as argument to publisher and subscriber, than publisher publish message.

Publisher - Code of Publisher class, which shows how publisher publish message using EventAggregator

 public class Publisher
    {
        EventAggregator EventAggregator;
        public Publisher(EventAggregator eventAggregator)
        {
            EventAggregator = eventAggregator;
        }

        public void PublishMessage()
        {
            EventAggregator.Publish(new Mymessage());
            EventAggregator.Publish(10);
        }
    }

Subscriber - Code of Subscriber class, which shows subscriber subscribe to messages which it interested in using EventAggregator.

    public class Subscriber
    {
        Subscription<Mymessage> myMessageToken;
        Subscription<int> intToken;
        EventAggregator eventAggregator;

        public Subscriber(EventAggregator eve)
        {
            eventAggregator = eve;
            eve.Subscribe<Mymessage>(this.Test);
            eve.Subscribe<int>(this.IntTest);
        }

        private void IntTest(int obj)
        {
            Console.WriteLine(obj);
            eventAggregator.UnSbscribe(intToken);
        }

        private void Test(Mymessage test)
        {
            Console.WriteLine(test.ToString());
            eventAggregator.UnSbscribe(myMessageToken);
        }
    }

Output


Note:
In practical scenario i.e. in actual application, one need to create EventAggregator at application start point i.e. at entrypoint of app and pass instance of publisher and subscriber.

For Example in Windows application create EventAggregator in Main() Method as in above example code, in Web Application create publisher in Appication_Start method of Global.asax or make use of Dependency Injection in which you register your publisher and use container to create when needed.

Event/Delegate Vs. EventAggregator

Difference between Event/Delegate and EventAggregator is
Event/Delegate EventAggregator
For publishing Different type of message there is need of creating different type of Publisher
For Example : Publisher - for integer type publisher Publisher - for string type publisher So the if class want to publish different type of messages it require to consume or create different type of publisher.
To publish integer abd string type message publisher class will be Publisher (Publisher intPublisher, Publisher strPublisher).
As EventAggregator works as HUB there is no need create more than one instance of Eventaggregator and publisher just need to consume it. Example: Publisher(EventAggregator eventAggregator)
Tight Coupling bettwen Publisher and Subscriber. In this pattern Subscriber require to know publisher as they subscribe to event of publisher. Loose Coupling between Publisher and Subscriber. In this pattern as EventAggregator is mediator Publisher and Subscriber don’t know each other they just need to know EventAggregator.

Conclusion

It's my Point of view , Event/Delegate is easy to implement and good for the small project or in project where there are less number of Publisher/Subscriber. EventAggregator is suitable for the large project or project which is having large number of Publisher/Subscirber.

But I think its always good to use EventAggregator because its offer loose coupling.

NOTE
It's my point of view please do comment on this and provide your feedback. Thanks to Sacha Barber to helping in update.

Saturday, January 18, 2014

Dependency Injection Part - 1

In this Article I am going to discuss about "Dependency injection" on which I am working and exploring. In this article I am going to discuss about what is dependency injection and why there is need of this software design pattern.

Dependency injection

To understand dependency injection better way, let’s consider below code,

Public class client
{
     Public static void main()
     {
        NeedDependencyClass a = new NeedDependencyClass();
     }
}

public class NeedDependencyClass
{
  Private readonly DependencyClass _b;
  public NeedDependencyClass ()
  {
     _b = new DependencyClass();
  }
  public void Test()
  {
     _b.Test();
  }
}

public class DependencyClass
{
  public void Test()
  {
    // code for text method
  }
}
In above code class client creates NeedDependencyClass and use it, then class NeedDependencyClass consume service of class DependencyClass to perform task i.e. class NeedDependencyClass is depend on class DependencyClass to perform task. This kind of the code is hardcoded dependency.
Image above shows the representation of creation and use of the objects.


Problem with code is
  1. Class NeedDependencyClass itself responsible for creating its own dependency.
  2. Code is tightly coupled, because dependency cannot be replaceable.
  3. Code also violate “Open Closed” rule of SOLID principal which says that "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification". Because do changes in the Test method I need to modify DependencyClass.
  4. Testing of Class NeedDependencyClass becomes difficult as I cannot replace Dependency class DependencyClass with other dependency.
Dependency injection is software development pattern which introduced to resolve above problems.

Definition of this pattern is: Remove hard coded dependency and make it possible to replace at run-time or compile time.

In following section I am going to describe how problem listed above get resolved with the Dependency injection pattern.

Solution

1)Make client i.e. first class in dependency graph which consume service to create all dependent object
Resolution to the first problem of code above, pass the responsibility of supplying all required dependency to the first in dependency graph i.e. client class which is first class of the dependency graph.

So the code will change like this

Public class client
{
     Public static void main()
     {
        NeedDependencyClass a = new NeedDependencyClass(new DependencyClass());
      }
}

public class NeedDependencyClass
{
  Private readonly DependencyClass _b;
  public NeedDependencyClass(DependencyClass b)
  {
     _b = b;
  }
  public void Test()
  {
     _b.Test();
  }
}

public class DependencyClass
{
  public void Test()
  {
    // code for text method
  }
}
Image below shows object creation only done by client class object and others class down the line use supplied defendant object.



2)Removes tight coupling between object i.e allow to define loose coupling
To understand the second problem better way, let’s consider with the real life scenario of Computer or laptop.
 

 

As you can see in the above image we have the port for each device external device to which I can associate external device and do our work.

But problem with this is I cannot attach my keybord on printer port and vice versa, same problem occurs with the other devices. So this is like tight coupling that I cannot change my external device on the give interface i.e. on which I am depends.

Solution to this is USB port.

If I have USB port than I can easily attach any device to my machine and perform my task.



What is tight coupling between classes? (In programming)

Let start with simple example:

public class NeedDependencyClass
{
  Private readonly DependencyClass _b;
  public NeedDependencyClass(DependencyClass b)
  {
     _b = b;
  }
  public void Test()
  {
     _b.Test();
  }
}

public class DependencyClass
{
  public void Test()
  {
    // code for text method
  }
}

Now as you see in above code class NeedDependencyClass utilized class DependencyClass, this means that class NeedDependencyClass is depend on class DependencyClass. This type of dependency is tight dependency between class NeedDependencyClass and class DependencyClass. Because class DependencyClass is passed as parameter to class NeedDependencyClass and class NeedDependencyClass utilizing method of class DependencyClass. Now if the why it called as tightly coupled. If code is like this to create

NeedDependencyClass a = new NeedDependencyClass(new DependencyClass()); 

now if I created class DependencyClass1 like as follows public

class DependencyClass1 { 
      public void Test() 
      { //code for text method } 
}

and I want to pass DependencyClass1 instead of DependencyClass in class and want to call test method

NeedDependencyClass a = new NeedDependencyClass(new DependencyClass1()); 

This will give compiler error because I am trying to pass DependencyClass1 object as parameter. So this means Class NeedDependencyClass cannot accept any another class than Class DependencyClass.

Solution to this problem is define and interface as below which get implemented by classes

Interface IDependencyClass
{
   Void Test();
}

Class DependencyClass : IDependencyClass
{
 ……
}
Class DependencyClass1 : IDependencyClass
{
 ……
}

So the code become like this

public class NeedDependencyClass
{
  Private readonly IDependencyClass _b;
  public NeedDependencyClass(IDependencyClass b)
  {
     _b = b;
  }
  public void Test()
  {
     _b.Test();
  }
}

And this code will work both the class DependencyClass and DependencyClass1

Image below shows DependencyClass object creation only done by client class object and others class down the line use supplied dependent object. And class NeedDependencyClass is depends on the interface IDependencyClass, which can be implemented and replicable by any new class DependencyClass.

3) Make your class depend on Abstraction
Now there is requirement like only authenticated user of the application can run Test method in the application, than developer of the class need to modify the Test method like this.

public class DependencyClass : IDependencyClass
{
  public void Test()
  {
    using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, 
        "YOURDOMAIN"))
 {
      bool isValid = pc.ValidateCredentials("myuser", 
       "mypassword");
               if(isValid)
         Console.Writeln(“Testing method for the data”);
               
 } 
  }
}

That’s violate SOLID principle “Open Close” which says "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification".

So to avoid it same as make use of the abstraction i.e. create interface as which already done for to resolve tight coupling, so class extension can be done easily.

Below is how to extend the code that doesn’t break “Open Close” principle.

Class DependencyClass : IDependencyClass
{
 public void Test()
  {
    Console.Writeln(“Testing method for the data”);
  }
}

Class SecureDependencyClass : IDependencyClass
{
  IDependencyClass _b; 
  public SecureDependencyClass(IDependencyClass b)
  {
    _b = b;
  }
  public void Test()
  {
    using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, 
        "YOURDOMAIN"))
 {
      bool isValid = pc.ValidateCredentials("myuser", 
       "mypassword");
               if(isValid)
         this._b.Test();   
               
 } 
  }
}

As you see in above code new class is created with the name SecureDependencyClass. This class extends the functionality of the previous class and also not breaks “Open Close” principle.

This is done by injecting exiting class DependencyClass in the new class SecureDependencyClass i.e that is also example of Dependency injection. So SecureDependencyClass consume dependency DependencyClass.

And which change consumer client code like as below

Public class client
{
     Public static void main()
     {
        IDependencyClass dependency = new SecureDependencyClass(new 
       DependencyClass());
        NeedDependencyClass a = new NeedDependencyClass(dependency);
      }
}

public class NeedDependencyClass
{
  Private readonly IDependencyClass _b;
  public NeedDependencyClass(IDependencyClass b)
  {
     _b = b;
  }
  public void Test()
  {
     _b.Test();
  }
}

Image below shows SecureDependencyClass object creation only done by client class object and others class down the line use supplied dependent object. And class NeedDependencyClass is depends on the interface IDependencyClass, which can be implemented and replicable by any new class SecureDependencyClass.


This also shows the NeedDependencyClass is not dependent on specific class but on the Abstraction.

4) Make class Testable
Now once the second step class NeedDependencyClass easily becomes testable. Because problem with original code is hardcode dependency that is not replaceable.

Example , following is the final code

public class NeedDependencyClass
{
  Private readonly IB _b;
  public NeedDependencyClass(IB b)
  {
     _b = b;
  }
  public int Test()
  {
     var c=_b.Test();
     return c*10;
  }
}

public class DependencyClass :IDependencyClass
{
  public void Test()
  {
    // code for getting value form database
    using(SqlConnection c = new SqlConnection(connectionstring))
    {
     c.open(); 
        SqlDataReader myReader = null;
SqlCommand    myCommand = new SqlCommand("select count(*) from table", c);
        return (Int32) cmd.ExecuteScalar();
  }
}

As per the code Test method of the class DependencyClass does connection with sql server and return value.

But for testing of the class NeedDependencyClass there is no need to perform expensive database connection. So we replace class DependencyClass with the TestDependencyClass class like as below.

public class NeedDependencyClass
{
  Private readonly IDependencyClass _b;
  public NeedDependencyClass(IDependencyClass b)
  {
     _b = b;
  }
  public int Test()
  {
     var c=_b.Test();
     return c*10;
  }
}

public class TestDependencyClass :IDependencyClass
{
  public void Test()
  {
     return 10;
  }
}

Public class TestClient
{
     Public static void main()
     {
NeedDependencyClass a = new NeedDependencyClass(new TestDependencyClass());
      }
}

Conclusion

So Dependency injection is one of important design pattern which allows developing maintainable code which also satisfies SOLID principals. DI not only helpful in above this problem but we can also achieve below, Other thing can be achievable by DI is
  1. Parallel programming of application
  2. Late Binding