Friday, January 15, 2010

Coupling

Coupling is even more critical than cohesion as a design principle.  Bad cohesion leads to comprehension problems, which (as a first order effect) leads to slower code modification.  Bad coupling leads directly to bugs.

Types of coupling (worst to best)

Content -  uses internal structure
Common - uses global data
External - externally imposed structure
Control - passing down a control switch
Stamp - composite parameters
Data - elementary parameters.
Message - no parameters
None - no coupling at all

You do need to couple to get anything done.  The key is to keep the coupling as loose as possible.

The more egregious forms of coupling are obviated my modern language design.  It is not possible to modify local variables from outside the routine they are defined in.  Globals are still possible, so discipline is required to not make use of them.

Polymorphism in OOP is the attack on control coupling.  Instead of passing down a flag to be tested, the controlling routine creates an object with the desired behaviour so the controlled routine does not have to handle any decisions.

The costs of stamp coupling can be mitigated by encapsulation.  If the external interface can be held constant it doesn't matter to the routine that the implementation has changed.

The Don't Repeat Yourself (DRY) principle is a powerful attack on the problems caused by coupling.  If the changes can be made in one place, and everything derives behaviour (correctly) from that definition, changes cannot cause bugs. Correctly is of course the key word there.  Careful data structure design is still required.

No comments:

Post a Comment