Single principle explanation

  • A class is allowed to have only one responsibility, that is, only one reason for the change of that class.

Interpretation of the

  • Changes in the responsibilities of a class are often the cause of class changes. That is to say, adding a class with multiple responsibilities will cause more changes in the class, making it difficult to maintain the class.
  • In daily development, as the business expands and requirements continue to increase, it is possible to add some responsibilities to the original class that do not belong to it, thus violating the single responsibility principle. If we find that the current class has more than one responsibility, we should separate the original deployment from the real responsibility of the class.
  • Not only classes, but also methods are subject to a single principle. That’s one way to do one thing. Rather than saying that there are different tasks in a method, you need to delegate different tasks to separate functions (methods).

advantages

  • Due to the responsibility of the classes and methods are divided into clear, though is likely to classes and functions (methods) the number of will change much, but doing so can improve the readability of the code, can also reduce the risk of application error, because of the clear code can quickly find the wrong place, a modified also won’t affect other function, reduce the cost of the code maintenance.

Analogy -> Programmer startup

  • A (full stack) programmer is about to start a business, and his original job is to write the required programs to complete the product. Start learning other skills.
  • Receiving projects, looking for investment, operating their own projects.

Entrepreneur 1 did not use the single liability principle

@property(nonatomic,strong)NSString *name; @property(nonatomic,assign)int age; Void programma; void programma; - (void)getProgect; // calculateMoney - (void)calculateMoney;Copy the code

Entrepreneur 2 uses the single responsibility principle

  • The development of

    @property(nonatomic,strong)NSString *name; @property(nonatomic,assign)int age; Void programma; void programma;Copy the code
  • Calculate the profit

    @interface Caculater: NSObject - (void)calculateMoney;Copy the code
  • Pick up the business

    @interface Projecter: NSObject - (void)getProject;Copy the code

practice

  • In actual development, it is important to separate the different responsibilities so that you can develop with me.