c# - 建议零售价 : Why use instance field values instead of parameters?

标签 c# parameters instance-variables single-responsibility-principle cohesion

我刚读过 SRP, as easy as 123… ,除了一个段落之外,所有这些都引起了我的共鸣,在一个名为“凝聚力”的部分中(我之前声称要“获得”凝聚力,但是关于参数与实例字段的讨论让我暂停......):

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.

这种删除参数是否只是一种临时练习,以揭示接近静态能力(低内聚性)的方法,其想法是您在完成后返回使用参数?

或者优先选择实例字段而不是参数是一种保持高内聚性的实际设计技术吗?

我是不是断章取义了?

最佳答案

CRUD 是一种真正通用的基于接口(interface)编程的方法。以实现 CRUD 接口(interface)的两个具体类为例:Employee 和 Building。

现在想象一下您的代码将如何基于参数:

Employee employeeObj = new Employee();
Building buildingObj = new Building();

string firstName = "Bob";
employeeObj.Create(firstName);

建筑呢?

BuildingTypes buildingType = BuildingTypes.One;
building.Create(buildingType);

Woops...你应该如何实现具有不同参数的 CRUD 接口(interface)?创建重载?更多接口(interface)?两个参数(名字姓氏)怎么样?

这会变得如此丑陋如此之快....因为一旦您将参数与 CRUD 界面一起使用,您就有不止一个更改的理由,这会降低设计的凝聚力。

让我们尝试使用基于对象/实例的参数...

Employee empObj = new Employee();
empObj.FirstName = "Bob";

empObj.Create();

Building buildingObj = new Building();
buildingObj.BuildingType = BuildingTypes.One;

buildingObj.Create();

通过简单的 CRUD 并且没有参数,我们甚至可以加入多态性:

someObj.Create();

这也导致了封装组合、解耦、SRP等……

关于c# - 建议零售价 : Why use instance field values instead of parameters?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4491338/

相关文章:

java - 抽象类变量和继承

c# - SQL Server SMO - 备份 - 如何确定失败/成功?

c# - 反编译C#时出现"PrivateImplementationDetails"函数

javascript - 如何将函数中的变量作为参数传递给匿名函数以充当变量

java - 如果枚举类是Java方法中的参数,如何获取枚举值?

flutter - 使用 StatefulWidget 标记为 @immutable 的类,实例字段不是最终的

c# - 如何使用 Machine.Fakes (Moq) 模拟 Function<>?

c# - 在 View 模型上收到的 radio 选择选择始终为 null,除了第一次选择

c++ - 加速的 C++ 头文件不起作用

java - 您什么时候需要公共(public)实例变量?