SOLID-SRP and OCP

I have been trying to improve on my software architecture and adopt some best practices, one of them is SOLID principles

Here are some points that i have gathered:

encapsulation + SOLID = object oriented design principles

The single responsibility(SRP) principle

There should never be more than one reason for a class change

Cohesion and Coupling

Strive for low coupling and high cohesion

Responsibilities Are Axes Of Changes

Lets see an example of a class diagram of a store that can receive payment on-line,cash and credit card

The problem

The result after the refactoring:

What is responsibility

Summary

The open/closed principle

The open closed principle states that software entities (classes,modules,functions, etc.) should be open for extension , but closed for modification

Open to extension- New behavior can be added in the future

Closed to modification- Changes to source or binary code are not required

Changes behavior without changing code?

In procedural code, some level of OCP can be achieved via parameters

The Problems with no OCP

Three Approaches to Achieve OCP

Lots of time we have code with lots of conditions, and we know that some were along the way we will add more conditions to the code

Lets say we have the function 'ComputeSomething' that calculates some thing according to some condition, we know that in the future we will have more conditions

The code can look like this:

public double ComputeSomething(SomeClass someValue)
       {
           if (SomeClass.has("Condition1"))
           {
               return 1;
           }
           else if (SomeClass.has("Condition1"))
           {
               return 2;
           }
           else if (SomeClass.has("Condition3"))
           {
               return 3;
           }
           return 4;
       }
   }

A nice solution to this is to use the strategy pattern(Depend on abstraction pass in implementation)

Now we only need to add new "ICondition" class and add it to the list, we separated the implementation of the calculation and the condition matching to another class:

public class BetterImplementation
  {

      List<ICondition> _conditionList;
      public BetterImplementation()
      {
          _conditionList = new List<ICondition>();
          _conditionList.Add(new condition1());
          _conditionList.Add(new condition2());
          _conditionList.Add(new condition3());

      }
      public double ComputeSomething(SomeClass someValue)
      {
          return _conditionList.First(e => e.IsConditionTrue(someValue)).Calculate(someValue);
      }
  }

  internal interface ICondition
  {
      bool IsConditionTrue(SomeClass someClass);
      double Calculate(SomeClass someClass);
  }

When do we apply OCP?

Summary