开发者

SRP: Why use instance field values instead of parameters?

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 o开发者_Go百科r 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?


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:

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

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

What about building?

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

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

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

empObj.Create();

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

buildingObj.Create();

With simple CRUD and no params one can even sprinkle in polymorphism:

someObj.Create();

This also leads to encapsulated composition, decoupling, SRP, etc...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜