SRP:为什么使用实例字段值而不是参数?
我刚刚阅读了 SRP,就像 123... 一样简单,除了名为“内聚”的一节中的一段之外,所有这些都引起了我的共鸣(我之前声称要“获得”内聚,但是参数与实例字段的讨论给了我暂停...):
上课。看看你的方法。 他们有参数吗? 使用实例字段?如果他们是 使用参数,删除它们。制作 它们是实例字段。你最终会吗 与仅使用其中之一的方法 五个实例?最有可能的是 警告低内聚力 存在于该方法和你的之间 类。
删除参数是否只是一个临时练习,以揭示接近静态能力(低内聚力)的方法,其想法是在完成后返回使用参数?
或者对实例字段优于参数的偏好是保持高内聚性的实际设计技术吗?
我是否断章取义了这句话?
I've just read SRP, as easy as 123…, and all of it resonates with me except one paragraph, in a section named "Cohesion" (I've claimed before to "get" Cohesion, but this talk of parameters vs instance fields gives me pause...):
Take your class. Look at your methods.
Do they have parameters or are they
using instance fields? If they are
using parameters, remove them. Make
them instance fields. Do you end up
with methods that only use one of the
five instances? That most likely is a
warning of the low cohesion that
exists between that method and your
class.
Is this removal of parameters merely a temporary exercise to reveal methods which are approaching static-ability (low cohesion), with the idea being that you return to the use of parameters when you're finished?
Or is the preference for instance fields over parameters an actual design technique to maintain high cohesion?
Have I somehow taken the quote out of context?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CRUD 是一种真正通用的基于接口的编程方法。采用两个实现 CRUD 接口的具体类:Employee 和 Building。
现在想象一下基于参数的代码会是什么样子:
构建怎么样?
哎呀...你应该如何实现具有不同参数的 CRUD 接口?创建过载?更多接口?两个参数(名字姓氏)怎么样?
这很快就会变得如此丑陋……因为一旦您使用带有 CRUD 接口的参数,您就有多个理由进行更改,这会降低设计的凝聚力。
让我们尝试使用基于对象/实例的参数...
通过简单的 CRUD 并且没有参数,我们甚至可以加入多态性:
这也会导致封装组合、解耦、SRP 等...
CRUD is a real common approach to interface based programming. Take two concrete classes that implement a CRUD interface: Employee and Building.
Now imagine how your code will look being parameter based:
What about building?
Woops...how are you supposed to implement CRUD interface with different parameters? Create overloads? More interfaces? What about two params (firstname lastname)?
This will get so ugly so fast....because as soon as you use parameters with a CRUD interface you have more than one reason to change, which decreases the design's cohesion.
Let's try using our objects/instance based params...
With simple CRUD and no params one can even sprinkle in polymorphism:
This also leads to encapsulated composition, decoupling, SRP, etc...