A Word About Cohesion
A Word About Cohesion
Let's start with a story. It's fictional, but it does mirror a real-life use case that I was involved with. In this
fictional story, we have to bill the hospital based on what their users do. Let's say a new medical record is created.
We would then bill the hospital a certain amount of money for that medical record.
To implement this, we first had to modify the MedicalRecordCreationService that created it. At the end of the
creation (after saving it to the database), we called another service, the MedicalRecordBillingService. That service
did whatever and then kicked off an asynchronous job that ran another service, the MedicalRecordBilliingJobService.
That did whatever and then called the MedicalRecordGenerateBillService which did the actual work to
bill the hospital.
What stands out is that each of these services was in a completely different place in the code base. They weren't even
in sub-packages within the same package. Nope, they were spread out across the code base.
That begs a question. If we are implementing a single Use Case (bill hospital when medical record is created), then
why is the code scattered? Can all the code to implement this Use Case be kept together in the same package?
And that brings us to another of my favorite topics: tracing execution flow. If I need to make a change to charging
for new medical records, I literally have to bounce around the code base to determine where to make the change.
For even more fun, consider the multilevel inheritance that I mentioned in the previous section. I have first-hand
experience trying to follow the flow of execution up and down the class hierarchy with ten levels. It's madness.
And that multilevel class hierarchy was also spread out over the code base.
I must also mention that it is generally accepted that developers spend about 20% of their time writing new code
and 80% of their time reading and trying to understand existing code. While we don't have exact numbers on
how much time is spent on each, my own experience validates these numbers. When the code for a Use Case is
scattered throughout the code base, it takes way more time and energy to understand it in order to make a
change.
The solution to all of this is simple: cohesion. Things that go together, stay together. It's that simple.
Keep the business logic for each Use Case together. Think cohesion and Vertical Slices.
©
Donald A. Barre. All rights reserved.