Solid Principles

SOLID Principles C#

  1. S – Single responsibility principle
    It means a class is responsible for only single entity, it should not contain multiple components. Like for example, if a class has an entity of Fetching Employee records, then it should not have fetching of Salary details.

  2. O – Open/Closed Principle
    Open for extension and closed for Modification, it means if I have an class and have multiple functions which are inter-related, if in future I want to add/modify the method I have to do it in the same class which is not a best practice. It’s good to have different classes by using single responsibility principle. By creating an Abstract class you can put common functionality in Abstract Base class and inherit those into derived classes. So here we are giving extension to derived classes via Base class.

  3. L- Liskov substitution principle
    You will have full implementation for your virtual method in parent class then we can easily replace this method in derived/child class. So, to avoid this thing we should use Interface which doesn’t have implementation in his Parent Class only definition.

  4. I – Interface Segregation principle
    Consumer of an interface should not be forced to use all of its methods, if the client does not want to or does not need them. If you have a BIG interface and it’s not inter-related then break those into multiple interfaces.

  5. D – Dependency Inversion Principle
    Inversion of control is the actual mechanism using which we can make the higher level modules depend on abstractions rather than concrete implementation of lower level modules. To achieve this we have to use Interface as Base class and we can inherit those Interfaces to base/Derived Classes.

    1. Dependency Injection is mainly for injecting the concrete implementation into a class that is using abstraction i.e. interface inside

      1. Constructor injection

        1. INofificationAction action = null;  
        2. public AppPoolWatcher(INofificationAction concreteImplementation) {  
        3.     this.action = concreteImplementation;  
        4. }   
      2. Method injection

        1. INofificationAction action = null;  
        2. // This function will be called when the app pool has problem  
        3. public void Notify(INofificationAction concreteAction, string message) {  
        4.     this.action = concreteAction;  
        5.     action.ActOnNotification(message);  
        6. }   
      3. Property injection

        1. INofificationAction action = null;  
        2. public INofificationAction Action {  
        3.     get {  
        4.         return action;  
        5.     }  
        6.     set {  
        7.         action = value;  
        8.     }  

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now