Thursday, November 7, 2013

Coupling and Cohesion (a revisit to my college days) Part 2

This is the second part of a 2 part post covering coupling and cohesion.  Want to see my thoughts on Coupling?  Get it here.  It's free, gosh darn it!

I'm going to discuss Cohesion in this post.  Cohesion always gave me problems because it's abstract and I mentally mixed the word "cohesion" with "adhesion".  When your brain does that do you, you're in trouble.

Code Cohesion is a description of your code.  Your code's completeness and degree that it is whole is cohesion.  When my mind thinks of the word "cohesion", I think of "cohesive".  After thinking about this a bit, it seems to make more sense to think of the word "coherent".  You may ask yourself, "is your class or set of functions coherent?  Does it make sense?  Does it have only one responsibility?  Is it complete?"  A class with a low amount of cohesion means that this class performs tasks that are not related to each other.  A great example of this would be a milkman class that delivers milk, the newspaper, and fathers your wife's next child.  You really want a high level of cohesion.  You really do.

So, you want high cohesion.  Why?  High cohesion means your code is coherent, it makes sense, it's concise, it tells the whole story, it is....  complete with a nice little bow.  Low cohesion means your code makes little sense and nothing is where it belongs.  Low cohesion is a sock drawer with kitchen knives.  High cohesion is a well organized sock drawer with no loose socks (and no knives).

No comments:

Post a Comment