Single Responsibility Principle (SRP) in 100 seconds

richardwynn

Richard Wynn

Posted on May 31, 2021

Single Responsibility Principle (SRP) in 100 seconds

๐Ÿ’ก 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

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
richardwynn
Richard Wynn

Posted on May 31, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About