Question

I was reading Robert Martin's Clean Code and in that he mentions about the code being highly cohesive:

Classes should have a small number of instance variables. Each of the methods of a class should manipulate one or more of those variables. In general the more variable a method manipulates the more cohesive that method is to its class. A class in which each variable is used by each method is maximally cohesivemethod is maximally cohesive

But when we are trying to write concurrent code, we strive to limit the scope of variables to a single method to avoid race conditions. But this results in code which is least cohesive.

When designing an application/class, what should you prefer - Cohesion or Concurrency?

Was it helpful?

Solution

I like quite a few of Martin's concepts, but your code needs to execute correctly and if it doesn't, all the beautiful metrics in the world aren't going to make you look better.

Add to that that threading issues are among the worst there are to debug, and you should not compromise your design for concurrency to conform with your idea of what someone wrote in a book about cohesion. Again, I'm not knocking Martin... I'm sure he'd tell you the same thing. After all, he recognizes that almost everything is on a continuum in most of his writing.

I'm not sure you're putting the emphasis in quite the right place though (could just be the way I'm reading your question). Martin's not saying you should make as many variables live at the class level as possible. He's saying that of the class level variables, how many are you using? If you promote variables you don't need to, you might not be getting higher cohesiveness... you might be getting tighter coupling.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top