What is the scope of the Single Responsibility Principle? [closed]

僤鯓⒐⒋嵵緔 提交于 2020-01-28 02:43:47

问题


Another engineer at my job asked me today about "what is this single responsibility thing?" and my answer was as follows:

"Every scope of your code, be it an if statement, a function, a class, a module, should have one reason to change".

But everywhere I read this, people talk in the context of a class. Was I wrong for telling him that SRP applies to every scope he has in his code?.


回答1:


Bob Martin has tried to clear this up on multiple occasions. The problem is that there are two different principles in play here; and it's extremely unfortunate that one of them doesn't really have a name, which is why it's commonly conflated with the SRP.

Functions should do one thing. They should do it well. They should do it only. --Clean Code (page 35)

That section of the book is simply titled, "Do One Thing" but it is not talking about the SRP. Martin makes this even more clear in his next book.

A function should do one, and only one, thing. We use that principle when we are refactoring... at the lowest levels. But it is not one of the SOLID principles–it is not the SRP. --Clean Architecture (page 62)

The best online explanation of the SRP is Martin's blog, which is summarized in the tag wiki. In the blog, and in his books, Martin is (fairly) consistent in using the term module to describe the scope in which the SRP applies. A module is simply a source file, and that usually just means a class file.

A module should be responsible to one, and only one, actor.



来源:https://stackoverflow.com/questions/56893910/what-is-the-scope-of-the-single-responsibility-principle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!