I know the idea of strong cohesion applies to methods as much it applies to classes. Just to be clear when I say strong cohesion of a method I mean a method which does only one task and does it well. This idea really works for simple getters and setters. But sometimes we usually come across methods that does more than one task internally , although it seems to be doing a single task if you look at a higher level of abstraction. An example of such a method can be :
public void startUp() {
List<SubSystem> subSystems = getSubSystems();
sychronized(subSystems) {
for (SubSystem subSystem : subSystems) {
subSystem.initialize();
}
}
}
And inside those subSystem#initialize()
methods a lot is going on. So is this a violation of the high/strong cohesion principle ?
0
No. It looks like it’s a cohesive method. You might rename the method “initializeAllSubsystemsOnStartup” and that’s probably more descriptive than “startUp”. Here’s a non-cohesive example:
public void updateCustomerOrders(Customer customer, Orders newOrders) {
if(!customer.isPersisted()) { customer.save(); }
else if(customer.inGoodStanding() {
customer.setOrders();
for(Order order in Orders) { order.setCustomer(); }
customer.save();
} else {
updateUi("Invalid customer");
}
}
It’s not cohesive because the method claims to be about updating customer orders (the lines in the else if block, but does many things, including possibly updating the UI which doesn’t feel like it should a concern at this layer.