DEV Community

loading...

Single Responsibility Principle (SRP) in 100 seconds

Richard Wynn
👋 Hi, I'm Richard Wynn, a Senior Full-stack Software Engineer with a joy of Coding, Writing and Sharing knowledge
・2 min read

💡 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.
Alt Text

👤 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.
Alt Text

💬 Quotes

  • A class should have one, and only one, reason to change. (Robert C. Martin) Alt Text

😮 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.
    Alt Text

📱 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:

📰 Other Programming Principles

Be interested? 😃 You can visit the links below read my other posts in my programming principles series

Discussion (0)