Wednesday, February 11, 2009

Coupling and Cohesion

As an overview, those two words are the top players in a game where you play with lots of OO cookies, if you can manage those two bad boys, you practically can get rid of all of your books about OO design. And yes, if you could compress all those book in to two little simple word it would be coupling and cohession.

it's about flexibility, reusability, extensibility, maintainability, portability, and so on, when you learn or use patterns, they all come down to these words, so what is coupling and cohession, really ?

coupling is about how much dependency between two separate module, the higher the worst it get. why is high coupling is bad ?, because when two seperate module is too dependent with one another, it would be difficult to modify them, imagine if module A depends on module B, and B on C, and C on D, if you try to modify A, you'll end up modifying most(if not all) other module, its a domino effect, one down, and everything else is just a matter of time.

While cohession is about how solid your module are, solid here means it does one thing it and it's very good at doing it, the higher the better it get, why is low cohesion is bad?, if you make a module that do stuff too much, you'll end up damping lots of logic in one place, which is bad because if any of those logic change, you might breaking other logic that sits in the same module. This is where the separation concern comes in, each module should only have one responsibility, if you have more than one reason to change a module, there is a big chance that module has low cohesion,

Ironic it is, but as you can guess, those two words are complementary, if you strive for one you'll get kick by another. for example if you want to make your module to have high cohession, you'll tend to squeeze it as much as possible, and by the end of the day that module will need to communicate to many other module to accomplish a bigger task, and then you'll realize that you had a high coupling. In other hand if you want to make less chit chat between modules, you'll end up with one big chunk of module which mean it has low cohession.

A good design is a harmonic balance between coupling and cohession.

whhatt is that? how you do "harmonic balance" ? how much is high, and how less is low? well I cant really tell as I'm still learning, but one thing I can tell is that a harmonic balance is not a 50:50 share, it depends on a dozen of variable, necessity, point of view, probability of change, difficulty, scenario of use, etc.. sometime you get to sacrifice one for another, and sometime we just can't figure it out...

1 comment:

genzoeri said...

just visit your blog, keep posting :)