design-patternsdesign-principlescouplingcohesion

When does improving program cohesion worsen coupling?


I recently took an exam on design principles & patterns, and one of the questions in the exam was as follows : "Sometimes improving program cohesion may worsen coupling, give an example."

From what I understand, cohesion is how focused a class/module is on fixing a problem it was created to fix, or better, how good is it at doing it job. Does it do jobs it should not be doing? Then move that part to a different class/module.

Coupling is the level of dependency between many classes/modules. Meaning that a good class/module will work regardless of whether or not we introduce major changes to a different module/class.

A way I used to explain this to myself is this example : A bartenders job is to make coffee and other drinks. A good bartender should do his job, which is making said coffee, and this increases his cohesion, but if he starts mopping the floor and serving customers, he is breaking away from his job, and thus the cohesion is lost. A good bartender also should not be affected by other staff members, meaning that his coupling is low. I other words, if the cleaning lady does not show up to work one morning, his job should be unaffected.

So if my understanding is correct, this means that increasing cohesion should not have a negative impact on coupling, just like telling a bartender to focus on coffee more won't make him more dependent on the cleaning lady.

Am I missing something? Is my understanding of cohesion/coupling flawed? Sorry for the long read!


Solution

  • If the staff of a bar is very cohesive they know each other's jobs and can work more effectively as a team. For example, a cocktail waitress might know where the bartender likes to take back dirty dishes (the portion of the bar near the dishwasher) so the waitress will drop off empty glasses there. Or the manager might notice the bartender is getting low on ice and go to the back of the house to get more and refill it without needing to be asked.

    Of course, by knowing each others jobs, the staff is now more tightly coupled. This might mean that any change in process would affect more people and create a training issue. For example, if the bar decided to switch from cubed ice to crushed ice, the manager would have to be told, or else he might get the wrong kind of ice. If the team were loosely coupled, only the bartender would need to know.

    From this example you can see that a very cohesive team needs to know each others' jobs which makes it harder to change any individual job. This corresponds to the maintainability issue created by tightly coupled modules in software. It's convenient, and lets the modules work more closely together, but it creates a problem if things ever change.