@BethCodes shared this simple summary of coupling and cohesion:
how many things change, with each additional thing making the change less safe, and how much of each thing, with more of each thing making the change safer
In the first part we talked about coupling. Coupling forces you to change more things at once. People understand that. Heck, you can find coupling by grepping for “make sure” in your code base, as in, “// when you change this make sure you change that too”.
Cohesion, now, cohesion is trickier. “How much of each thing, with more of each thing making change safer.” How does that work? Let’s say you have a 5 line function. In order to change the behavior of the system you have to change all 5 lines at once. Easy (relatively) peasy.
Put those 5 lines in the middle (or worse, scattered around) a 100-line function. Now you have a problem. Which of the preceding lines matter for the change you want to make? Which of the following lines are affected by the change you want to make?
This leads to the seeming paradox that the more coupled an element is, the better. But only inside the element. If changing 1 line of a function requires changing all 4 other lines, excellent! The lines of the function are completely coupled, so change is quicker, safer, easier.
I was pairing with a long-time student once. We needed to change 2 out of 10 lines of a function. Out of habit? Reflex? Experience? they extracted those 2 lines as a helper function, changed the 2 lines, then inlined the helper back into the original function. That’s leveraging cohesion.
The resolution of the paradox is that if you increase coupling inside of an element you tend to decrease coupling outside of it.
It can be difficult to see how to de-couple elements. Increasing cohesion, on the other hand, is easier to imagine. That’s what the tidyings are, ways of increasing cohesion at the smallest scale.
Thank you, @BethCodes 🙏🏽.
Something interesting strikes me when I read:
"It can be difficult to see how to de-couple elements. Increasing cohesion, on the other hand, is easier to imagine."
Even if the two practices are the same, I.E. de-coupling and increase cohesion (I'm not saying they are but even if the were), there is a difference in direction. We de-couple away from something, almost fleeing from something. We increase towards something, cohesion.
As people we tend to work better going towards a goal than away from something. So it makes sense on a deeper psychological level as well that it's easier to increase cohesion than to de-couple.
I'm not thinking about cohesion. Or coupling. Or decoupling. My first concern is (single) responsibility. Inside a responsibility I get cohesion. By separating responsibilities I get decoupling.