Measuring Cohesion - The LCOM principle
There has been a constant doubt in my mind since I got to know about the pattern of developing applications based on DDD. Still a novice, I quite frequently come across situations where I'm not sure what the best place to put a particular piece of functionality is. I take a calculated risk, quite often a wrong one, trying to assess the after effects.
I recently came across this great read on cohesion. What should be a "good enough" basis for deciding how cohesive should different pieces of functionalities be. And I particularly loved the example provided:
Considering two different implementations of the same functionality:
Class A{
getDevices()
createDevice()
modifyDevice()
removeDevice()
repairDevice()
diagnoseDevice()
}
It's quite logical to think of all the methods to be directly related to a device. But upon a closer look, one might say that the last two methods only deal with troubleshooting the device. Should the last two methods then sit inside a TroubleShootDevice class?
Depends. Do we think troubleshooting can potentially come up as some sort of a major functionality in our domain? Does troubleshooting involve a lot more than just a device? Then yes. Otherwise it's quite okay to keep it within the same class.
Not saying this is the best approach. There are definitely better approaches out there and a lot more reasoning than just what I said above. But this helps in shaping our decisions. Above all, this is something I personally encounter quite frequently. The LCOM principle is a great aid in determining the level of cohesion in classes.
All credits to Fundamentals of Software Architecture for explaining this in an amazing manner.