Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top