Why coupling will destroy your application and how to avoid it

Left unchecked, tight coupling between components (especially when distributed around your application) can slowly kill your software; rendering it hard to maintain and much more likely to suffer from bugs.

In software engineering, coupling is the manner and degree of interdependence between software modules; a measure of how closely connected two routines or modules are; the strength of the relationships between modules.

When developing software, we tend to keep a mental picture of the software we write as we go along. This is why developers so oftencomplain about interruptions; because it takes time to build that mental map of the problem you’re working on and any interruption can set you back causing you to pick up the pieces and start building the picture again.

Even when you split your code into multiple classes you have knowledge of the “other half” of the equation (the calling or called classes).

Born together

As a result, it’s easy to couple the software together. At the exact moment you write the code, the coupling is hidden from you because your mental map encompasses both halves of the solution. In effect it is entirely possible to simply take an implementation, divide it in half and spread it between two classes. The two classes end up depending on each other and consequently they are forever joined and rippling changes are inevitable.

Probably the most blatant coupling you’ll ever see in code is magic strings. As soon as we use “Apple” in two places we’ve coupled our code together. It only takes one of them to be renamed to break our application.

When it comes to how damaging this coupling is, distance matters.

We can weaken the coupling by bringing it closer together. If these two strings exist within the same small method then the coupling may well be manageable. Anyone who looks at the code will see both usages of the string and understand that changes to the declaration will affect the usage.

But when the coupling is spread around your app then the risk of bugs dramatically increases.

Coupling is usually contrasted with cohesion. Low coupling often correlates with high cohesion, and vice versa. Low coupling is often a sign of a well-structured computer system and a good design, and when combined with high cohesion, supports the general goals of high readability and maintainability.

By providing our shopping cart with a coping strategy for missing items, we’ve ensured that the calling application retains control of the details of how to handle the error and our shopping cart need only execute the provided coping strategy when it makes sense to do so.