Pranay Rana: Software design Principle
Showing posts with label Software design Principle. Show all posts
Showing posts with label Software design Principle. 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, July 13, 2015

SOLID Principle In Detail

SOLID principles are the set of principle fist given by Robert.C.Martin. SOLID principle as name given its set of principle that allows building SOLID software system (i.e. Application, Application Module), if one implement software according to this set of principle.

SOLID software system means its allows to build system that is
  • Easy to maintain
  • Easy to extend
  • Easy to understand
  • Easy to implement
  • Easy to explain
SOLID principles are related with the design and maintenance of software system. Most of the developer mix SOLID principles with OOD principles and Design patterns. Below image that removes confusion of OOD principles and Design patterns
Note: This is my interpretation of the arranging thigs.

So as per image

  1. OOD Principle (Abstraction, Encapsulation, Inheritance, Polymorphism)
  2. SOLID principle
  3. Software Design Patterns (GOF patterns, Dependency injection & patterns)
  4. Martin Flower’s Enterprise Application Architectures Pattern (additional but required)
  5. Domain Driven Design Architecture (additional but required)
S.O.L.I.D is acronym for

  1. Single Responsibility Principle

    Principle is related to Designing software module, class or function that should perform only one task. So this principle is about Creation.


    In Detail Read : Single Responsibility Principle In Detail

  2. Open/Close Principle

    Principle is applied after 1 (Single Responsibility Principle), again this principle is related to Designing module, class or function. But it about closing already designed thing for modification but opening designed thing for extension i.e. extending functionality. So this principle is about extension.


    In Detail Read : Open Closed Principle
  3. Liskov Substitution Principle

    Principle is related to substitution of child in place of its parent. So principle is about relationship i.e. inheritance.


    In Detail Read : Liskov Substitution Principle
  4. Interface Segregation Principle

    Principle is related to designing of interfaces as one of the basic rules of designing says depends on abstraction. Principle is about design interface such a way, so that client of interface not force to implement not required things. So principle is about efficient interface design.



    In Detail Read : Interface Segregation Principle

  5. Dependency Inversion Principle

    Principle is related to designing decoupling modules, classes of software system. This principle mostly applied after 4 (Interface Segregation principle) because interface are one form of abstraction and this principle is related to Details (module/class) should depend on abstraction, and abstraction should not depend on detail. So this principle is about creating loosely coupled system.


    In Detail Read : Dependency Inversion Principle

Dependency Inversion Principle

The Dependency Inversion Principle is one of the SOLID principles defined by Robert C. Martin. This principle is about dependencies among the components (such as two modules, two classes) of the software.

The principle says that high-level modules should depend on abstraction, not on the details, of low level modules, in other words not the implementation of the low level module. Abstraction should not depend on details. Details should depend on abstraction. In simple words the principle says that there should not be a tight coupling among components (in other words two modules, two classes) of software and to avoid that, the components should depend on abstraction, in other words a contract (interface or abstract class).

Dependency Inversion Principle in Real life

To understand the second problem better way, let's see a real life scenario of a computer or laptop.




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

But the problem with this is, I cannot attach my keyboard to a printer port and vice versa. The same problem occurs with the other devices. So this is like a tight coupling, that I cannot change my external device on the given interface, in other words on which I depend.

Solution to this is USB port.

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



Example of Dependency Inversion Principle in Application Development

The following is a class diagram of tight coupling that does not follow the principle.



Public Class Customer  
{  
    CustomerRepository CustomerRepository;  
    Public Customer  
    {  
        CustomerRepository = new CustomerRpository();  
}  
  
Public bool Save()  
{  
    CustomerRepository.Save();  
}  
}  
  
Public class CustomerRepository  
{  
    Public bool Save(dattype data)  
{  
              //Sql Connection object and Save data in Sql server   
}  
}  

The preceding code is tightly coupled because the current repository deals with the SQL server. So if the requirement is to use an Oracle server then there is modification required for the Customer class.

So to avoid that, make the customer class depend on abstraction. The following is an image of a class diagram where the customer depends on abstraction and supports both SQL and Oracle servers.



Public Class Customer   
{  
    CustomerRepository CustomerRepository;  
    Public Customer   
    {  
        CustomerRepository = new CustomerRpository();  
    }  
  
    Public bool Save()   
    {  
        CustomerRepository.Save();  
    }  
}  
  
Public class CustomerRepository   
{  
    Public bool Save(dattype data)   
    {  
        //Sql Connection object and Save data in Sql server     
    }  
} 

So in the preceding code the customer class depends on ICustomerRepository abstraction, in other words an interface. Another thing is here the customer class receives a dependency via consumption of the customer class or using a dependency container.

Note: Here is an example of the class but the same goes for the modules designed in software because dependency inversion is about providing a set of abstraction policies on which the details depend and the policy that provides flexibility in the software system.

Disadvantages

Application modules become tightly coupled, that means:
  1. The testability of the module becomes difficult.
  2. Parallel development of the module becomes difficult.
  3. Many changes are required when there is modification in the module and when there are changes in the module it depends on. 
Read more Dependency Injection talks about the disadvantages and advantages of using dependency inversion.

Note: Dependency Injection is not the same as Dependency Inversion because Dependency Inversion is about defining an abstraction policy for the software module whereas Dependency Injection is a set of patterns to supply dependency.

Interface Segregation Principle

The Interface Segregation Principle is one of the SOLID principles defined by Robert C. Martin. It is one of the rules of software development that says to always code according to a contract, in other words an interface, not against the implementation, in other words a concrete class, because coding against an interface provides advantages like flexibility, loose coupling, testable code and so on. This principle is related to creating an interface for implementation.

The principle says “Client (class implementation interface) should not force to implement Interface that they don't use.” In simple words the principle is saying, do not design a big fat interface that forces the client to implement a method that is not required by it, instead design a small interface. So by doing this class only implement the required set of interface(s).

If there is big fat interface then break it into a set of small interfaces with the related method(s) in it. It's similar to normalizing our database like normalizing database from 1NF to 3NF where a big table is broken into tables with related columns.

Interface Segregation Principle in Real life

In terms of the violation of the ISP, the following image shows a big dustbin for throwing all kinds of garbage away without any kind of segregation.



With ISP, the following image is a good example of segregation in our real life.




That is an image of a waste bin segregation that shows which one to use for throwing away trash we use.

Example of ISP in Application Development

Here is an example of a banking customer for a bank with the following types of customers:
  1. Corporate customer: For corporate people.
  2. Retail customer: For individual, daily banking.
  3. Potential customer: They are just a bank customer that does not yet hold a product of the bank and it is just a record that is different from corporate and retail.
The developer of a system defines an interface for a customer as in the following that doesn't follow the ISP rule.



It looks OK at first glance but it's a big fat interface for the customer with problem since it forces the client class to implement methods that are not required.
  1.  A potential customer as described taht does not hold any product is forced to implement a product property. 
  2. A potential customer and a retail customer both are forced to have a Customer Structure property but in a real scenario a Corporate customer has a Customer Structure that describes a customer hierarchy. 
  3. A potential customer and a retail customer both are forced to implement a BusinessType but that just belongs to a corporate customer. 
  4. A corporate customer and a potential customer are forced to implement an Occupation property that is just a blog to a retail customer. 
A solution to the preceding problem is to split the fat interface into meaningfull parts, in other words small interfaces, so the customer type only implements the interface that is required by it.

The following is an image that follows the ISP:



Disadvantages
  1.  Deliver big fat interface that forces the client to implement a method that is not required.
  2. The client ends up implementing a usefuless method, in other words a method that has no meaning to the client. This decreases the readability of the code and also confuses the developer using the client code.
  3. The client interface ends up violating SRP sometime since it might perform some action that is not related to it.

Liskov Substitution Principle

Liskov Substitution Principle – is one of the SOLID principles defined by Barbara Liskov. Principle is based on the parent-child relationship in other words inheritance features of OOD (Object Oriented Design). Principle says “When class S is a subtype of class T then an object of type T can be replaced by an object of type S without affecting functionality/correctness of the implementation or program”.

In simple words it says “Places in implementation (Class/Function) that use a base class, in other words consume a service of a base class, must work correctly when the base class object is replaced by a child class (derived class) object.”

Liskov Substitution Principle in Real life 

The following is an example of an electric bulb that actually violates substitution. When the bulb fails it is replaced with a new bulb. Here in this example the old bulb is replaced with the new bulb.

Perfect Substitution


Note:
Here in this example in the family of bulbs, considering the old bulb to be a parent of all bulb types and a CFG bulb is a child of the same family inherited from it.

When one replaces a failed bulb, in other words in programming terms substitutes the old with the new, it must provide light that is provided by the old bulb, in other words works without affecting correctness or functionality (provides a constant light in the house). In the preceding example the substitution worked perfectly since there is no modification in functionality.

Violation Example



The preceding image shows the violation of the principle. Since replacing with a decoration bulb (that provides light in the form of decoration) instead of a bulb meant for just providing light in the house. That actually is a violation in the sense of modifying the functionality because a decoration bulb does not provide the same functionality for the consumer.

Example of not following Principle in Application Development



Continuing with bank savings account that is already explained in previous articles about the Open-Closed Principle.
 
Interface ISavingAccount   
{   
   //Other method and property and code   
   bool Withdrwal(decimal amount);   
}   
   
Public Class RegularSavingAccount : ISavingAccount   
{   
  //Other method and property and code related to Regular Saving account   
   
   Public bool Withdrwal ()   
  {   
    Decimal moneyAfterWithdrawal = Balance-amount;   
if(moneyAfterWithdrawal >= 1000)   
{   
    //update balace    
    return true;   
}   
else   
  return false;   
  }   
}   
   
Public Class SalarySavingAccount : ISavingAccount   
{   
  //Other method and property and code related to Salary Saving account`   
   Public bool Withdrwal ()   
  {   
    Decimal moneyAfterWithdrawal = Balance-amount;   
    if(moneyAfterWithdrawal >= 0)   
    {   
       //update balace    
       return true;   
    }   
    else   
      return false;   
  }   
}   
Public Class FixDepositSavingAccount : ISavingAccount   
{   
  //Other method and property and code related to Salary Saving account`   
   Public bool Withdrwal ()   
  {   
    Throw New Excpetion(“Not supported by this account type”);   
  }   
}   

In the preceding code the IsavingAccount interface is implemented by a different kind of savings account of the bank, like Regular, Salary and FixDeposit savings account.

But as per the banking rules, a FixDeposit savings account doesn't provide a withdrawal facility whereas another bank account might provide a withdrawal facility.

So the developer might write code to raise an exception when an attempt is made to withdraw from a FixDeposit savings account.

Now consider the following method in a class calling a withdrawal by casting the actual object to the parent class type.

Public class AccountManager   
{   
    Public bool WithdrawFromAccount(IsavingAccount account)   
    {   
         account.Withdraw(amount);   
    }   
}   

The following code calls the method,

//works ok  
AccountManager.WidhdrawFromAccount(new RegularSavingAccount());  
//works ok  
AccountManager.WidhdrawFromAccount(new SalarySavingAccount());  
//throws exception as withdrawal is not supported  
AccountManager.WidhdrawFromAccount(new FixDepositSavingAccount()); 

Violation of Liskov Substitution Rule

So the preceding code breaks the Liskov Substitution rule since the inherited FixDepositSavingAccount class is modifying the functionality of the withdrawal. Because the savings account should provide functionality to withdraw an amount without throwing any error.

How to stop violating the rule

To stop violating the rule one must verify the inheritance tree, in other words child classes inherited from the parent class should not break the functionality when the child class object replaces the parent class object.

So the class must inherit from the proper parent class in such a way that when the child class replaces the parent, it doesn't break the actual functionality provided by the parent class.

Note
It's not always true that one must make changes in the inheritance tree but making changes at the class and method level also resolves problems. To get such kind of example click on the link: Object Menter (Square and rectangle example).



In the preceding image the new classes WithWithdrawal and WithoutWithdrawal are created and the child classes are inherited from the respective parent class.

So in the preceding code:

Interface ISavingAccount   
{}   
Public Class SavingAccountWithWithdrawal : ISavingAccount   
{   
    Public virtual bool Withdrwal () {}   
}   
Public Class SavingAccountWithoutWithdrawal : ISavingAccount   
{   
}   
Public Class RegularSavingAccount : SavingAccountWithWithdrawal   
{    
  Public bool Withdrwal ()   
  { //implementation   
  }   
}   
Public Class SalarySavingAccount : SavingAccountWithWithdrawal   
{    
  Public bool Withdrwal ()   
  {//implementation   
  }   
}   
Public Class FixDepositSavingAccount : SavingAccountWithoutWithdrawal   
{   
}   

Now using it:

Public class AccountManager   
{   
    Public bool WithdrawFromAccount(SavingAccountWithWithdrawal account)   
    {   
       account.Withdraw(amount);   
    }   
}   


Now the following code to call method:

//works ok  
AccountManager.WidhdrawFromAccount(new RegularSavingAccount());  
//works ok  
AccountManager.WidhdrawFromAccount(new SalarySavingAccount());  
//compiler gives error   
AccountManager.WidhdrawFromAccount(new FixDepositSavingAccount());  

Disadvantage of not following the Liskov Substitution Principle
  • Developed code throws a run time error or exception or also might not work as expected and that leads to program failure or incorrect results.
  • The preceding discussion shows an example of throwing an exeption by a child class for a not supported method.
  • Read link: Object Mentor that shows an example (square and rectangle example) of giving incorrect results when not following the principle.
So the biggest advantage of not following this rule is: it causes problems at runtime rather than causes application failure or incorrect results.

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