Single Responsibility Principle or SRP

An object should contain only a single responsibility, and that responsibility is fully encapsulated in a class. The single responsibility principle simply means that each class has only one responsibility, that is, each class has only one reason for its change.

The sample

public class Rectangle : Shape {

    public int Height;
    public int Width;

    public int Area() {
        return Width * Height;
    }

    public void Draw() {
        Console.WriteLine("Draw Rectangle!"); }}Copy the code

Rectangle class contains two exposed attributes and methods: The Area method calculates the Area of a Rectangle, and the Draw method draws the Rectangle. Two different types of operations, “calculate” and “Draw”, are coupled in the same class, which does not conform to the principle of a single responsibility. The following is a possible code for a caller.

public class CalculatorShapeArea {

    public void CalculateArea(Rectangle rectangle) {
        vararea = rectangle.Area(); }}Copy the code
public class DrawRectangle {

    public void Draw(Rectangle rectangle){ rectangle.Draw(); }}Copy the code
public enum DrawType {
    None,
    shadow
}
Copy the code

Note that the Area and Draw methods are called from a Rectangle instance, which is highly coupled. When we were ready to change the Draw method one day (for example, to add an enum parameter called DrawType to Draw to determine whether to use a shadow effect when drawing), the Rectangle class changed because the class had two factors that caused it to change: “calculate” and “Draw.” In practice, the Rectangle class can be a complex one, and changing the Draw method requires a full regression test to determine whether the change affects the correctness of the entire Rectangle class, so the consequences of such a change can be serious and costly. The following is a solution for your reference:

public class Rectangle : Shape {

    public int Height { get; set; }
    public int Width { get; set; }

    public int Area() {
        returnWidth * Height; }}Copy the code
public class RectangleDraw {

    public void Draw(Rectangle rectangle) {
        Console.WriteLine("Draw Rectangle!"); }}Copy the code
var rectangle = new Rectangle();
var area = rectangle.Area();

var rectangleDraw = new RectangleDraw();
rectangleDraw.Draw(rectangle);
Copy the code

The Draw method is re-encapsulated by the RectangleDraw class, separating “calculation” from “drawing”. When we want to add parameters to the Draw method, we just change the RectangleDraw method, which does not affect the Rectangle class, so we simply do a regression test for the RectangleDraw class, reducing the coupling of the RectangleDraw methods. Meet the requirements of the single responsibility principle.