views:

48

answers:

1

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?

+1  A: 

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.

Jim Leonardo
Thanks Jim. But my question is when you are looking at making your application concurrent, the ideal thing is to be least cohesive so that you need not synchronize your methods. I am just wondering if I invest too much time in making in making classes cohesive, I will be left with code which would be difficult to parallelize.
Ravi Gummadi
You're the one who maintains your code. Above all, do what you know you can do and have it work correctly. If I have to choose, and I know my app is multi-threaded, I will pick concurrency. But, I prefer to avoid situations where I have to choose.
Jim Leonardo