单一职责原则的范围是什么? [英] What is the scope of the Single Responsibility Principle?

查看:57
本文介绍了单一职责原则的范围是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我工作的另一位工程师问我这个单一职责是什么?"我的回答如下:

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

代码的每个范围,无论是 if 语句、函数、类还是模块,都应该有一个改变的理由".

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

但在我读到的任何地方,人们都在课堂上交谈.我告诉他 SRP 适用于他代码中的每个范围是错误的吗?.

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?.

推荐答案

Bob Martin 曾多次尝试解决这个问题.问题是这里有两个不同的原则;非常不幸的是,其中一个没有真正的名字,这就是为什么它通常与 SRP 混为一谈.

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.

函数应该做一件事.他们应该做得很好.他们应该只做.--清洁代码(第 35 页)

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

这本书的那部分标题很简单,做一件事",但它不是谈论 SRP.马丁在他的下一本书中更清楚地说明了这一点.

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.

一个函数应该做一件事,而且只能做一件事.我们在重构时使用该原则......在最低级别.但这不是 SOLID 原则之一——它不是 SRP.--简洁的架构(第 62 页)

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)

SRP 最好的在线解释是 Martin 的博客,在标签维基中进行了总结.在博客和他的书中,马丁(相当)一致地使用术语模块来描述 SRP 的适用范围.一个模块就是一个源文件,通常就是一个类文件.

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.

这篇关于单一职责原则的范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆