Hello everyone, I am han Cao 😈, a grass code ape 🐒 who has been working for more than a year. If you like my article, you can follow ➕ to like it and grow up with me. Add my wechat: Hancao97, invite you to join the group, learn and communicate together, and become a better engineer

This is the 8th day of my participation in the First Challenge 2022. For details: First Challenge 2022.

background

This is the sixth installment of my Architectural Cleanliness series, in which we will look at the SRP single responsibility principle

Clean Architecture Series:

  • Hancao’s book column on the Way to Neat Architecture

SRP single responsibility principle

The SRP principle is often misunderstood, and many programmers think it implies that each module should only do one thing.

However, this is not the case. The confused design principle is: a function does only one function. We often use this principle when refactoring complex functions, but this is only a design principle for low-level implementation details, not the whole SRP principle.

The SRP principle should be described as: any software module should only be responsible for a certain class of actors.

Here the actor refers to: one or more people with common needs.

A software module is a set of closely related functions and data structures, and the word “related” implies the SRP principle. Code and data are grouped by their relevance to a class of actors.

Here’s an example:

The Employee class in a payroll program has three functions: calculatePay(), reportHours(), and Save ().

  • The calculatePay() function is made by the Finance department, who report to the CFO
  • The reportHours() function is developed and used by the human Resources department, who report to the COO
  • The save() function is defined by the DBA, who reports to the CTO

In doing so, the programmer essentially couples the behavior of three actors together, violating SRP design principles

The solution to this problem is simple:

Divide related functions into different classes.

Or with the facade pattern shown above, the EmployeeFacade class only needs to contain functions that initialize and call the three concrete implementation classes.

conclusion

The single responsibility principle focuses on the relationship between functions and classes — but it takes different forms at both levels of discussion. At the component level, we can refer to this as the common closure principle, and at the software architecture level, it is the axis of change that sets architectural boundaries.

The last

✨ ✨ ✨ ✨ ✨ ✨ ✨ ✨ ✨ ✨ ✨ ✨ ✨ ✨ ✨

Youth never knows heaven and earth

Conceit and talent are everywhere you look

Pretentious as it is

I was honest

I love such a boy

Humble and arrogant

Proud and calm ☀️

✨ ✨ ✨ ✨ ✨ ✨ ✨ ✨ ✨ ✨ ✨ ✨ ✨ ✨ ✨

Your likes and attention are my constant motivation, you can add my wechat: HancAO97, invite you to join the group, learn and communicate together, become a better front-end engineer ~