๐ก What does SRP stand for?
The single responsibility principle (SRP) is a programming principle that states that every module, class or function in a computer program should have responsibility over a single part of that program's functionality, and it should encapsulate that part. All of that module, class or function's services should be narrowly aligned with that responsibility.
๐ค Origination
The term was introduced by Robert C. Martin (colloquially called Uncle Bob, an American software engineer, instructor, and best-selling author) in an article by the same name as part of his Principles of Object Oriented Design.
๐ฌ Quotes
- A class should have one, and only one, reason to change. (Robert C. Martin)
๐ฎ Why SRP?
- Functions/ Modules/ Classes that have only one responsibility are much easier to explain, understand, implement and test than a one-for-all one.
- Prevents unexpected side-effects of future changes. The more responsibilities your function/ module/ class has, the more often you need to change it.
๐ SRP Violation Smells
- One class currently depends on many other classes.
- Big classes with lots of methods.
- A function that has too many lines of code.
- Constantly interfere with other developers on the same function/ module/ class despite working on different functionality.
- Top n functions/ modules/ classes that changed most often.
๐ Side Notes
- Not oversimplify your code by creating classes with just one function. There is no point in having multiple classes that just contain one function.
๐ก Tips
Asking a simple question before you make any changes: What is the responsibility of your function/ module/ class/ etc?
If your answer includes the word and, you're most likely breaking the single responsibility principle. That's the time to take a step back and rethink your current approach to find a better one.
๐ฑ Keep in Touch
If you like this article, don't forget to follow and stay in touch with my latest ones in the future by following me via:
- Twitter: https://twitter.com/RichardWynn01
- Medium: https://richard-wynn.medium.com
- Github: https://github.com/richard-wynn
๐ฐ Other Programming Principles
Be interested? ๐ You can visit the links below read my other posts in my programming principles series
Top comments (0)