Monday, June 15, 2015

Single Responsibility Principle

              The single responsibility principle (SRP) instructs developers to write code that has one and only one reason to change. If a class has more than one reason to change, it has more than one responsibility.Classes with more than a single responsibility should be broken down into smaller classes, each of which should have only one responsibility and reason to change.
              The SRP is primarily achieved through abstracting code behind interfaces and delegating responsibility for unrelated functionality to whichever implementation happens to be behind the interface at run time. Some design patterns are excellent at supporting efforts to strictly regiment the SRP— in particular, the Adapter pattern and the Decorator pattern. The former enables much of your code  to maintain first-party references to interfaces under your direct control, although in reality utilizing  a third-party library. The latter can be applied whenever some of a class’s functionality needs to be removed but it is too tightly coupled with the intent of the class to stand alone.

Decorator Pattern: This pattern can also be used with events and properties(unless they use auto property)
The Composite Pattern :
The predicate Pattern :It is useful construct for hiding the conditional execution of code from clients
Branching Decorators :
Logging Decorators :
Limitations :
  • Any private state contained in the decorated class remains unavailable to the logging decorator,which cannot access this state and write it to a log.
  • logging decorator would need to be created for every interface in the application. logging is better implemented as a logging aspect(AOP in PostSharp)


Using the strategy pattern instead of switch :

            In the example, for each case of the switch statement, the behavior of the class changes. This presents a code maintenance problem because the addition of a new case option requires a change to this class. If, instead, you replace each case statement with a new implementation of an interface, further implementations can be created to encapsulate new functionality—and the client would not
need to change. This is shown as below




No comments:

Post a Comment