Wednesday, November 6, 2013

Coupling and Cohesion (a revisit to my college days)

This is the first of a 2 part series of blog posts discussing coupling and cohesion:

One curious set of words that bugged me when I was in school was Coupling and Cohesion.  Coupling and Cohesion were tough for me to get my head around.  It didn't help that they both started with a 'C' and I could visualize both words coming to a visual end of 'togetherness'.  For example, I could use a pipe coupling to fit 2 pieces into a single cohesive pipe.

For this post, I will limit my discussion to Coupling.

Code Coupling has to do with how one 'thing' fits with another 'thing' and how they depend on each other.  Let's say I have a 1" pipe. I need a 1" coupler if I'm going to connect it with anything else.  Likewise, if I have a function call that depends on something, that something is required if I'm going to use it anywhere.  A pipe connected to nothing is as useless as a function never called, so I'm forced to have a 1" coupler for the pipe and I'm forced to have that instance of an argument for the function call.  This is where the pipe metaphor gets good for developers:  I can change my function's dependency on a widget by defining an interface that the function can depend on instead.  An interface is simply a definition of a set of functions.  Where this gets interesting is thinking about the interface as something that is more related to the function and less related to the widget.  Since this interface is something the function depends on, why not think of it as having a stronger relationship to the function and less of a relationship to the widget?

So, you want low coupling.  Why?  With coupling, you want a low amount of dependencies on other things.  More dependencies on things outside of your domain means more changes more often.  More changes means you have a higher chance of making a mistake.  It's a numbers game, really.  More changes = more time = more mistakes = more time = less learning something new and cool.  Low coupling allows for easy interchangeability.  High coupling forces uncomfortable code.  Low coupling is being able to eat all the desserts.  High coupling is being able to only eat sugar.

No comments:

Post a Comment