Tuesday, October 9, 2018

The Bizarre Properties of Coupling

Coupling is one of the easiest code qualities to mistake because of its unusual properties.

For one thing, Coupling doesn't require that you have to do the work to find the consequent change but t also doesn't preclude the possibility.

For another, coupling isn't always obvious.

Imagine you have three classes, A, B, and C. A calls a method of B, which calls a method C with some of the parameters provided to A.

A diagram of what was described, immediately before this

Since A is coupled to the public interface of B, it's safe to assume changes to that contract will trigger changes in A. Hence, A is coupled to B's public interface.

B's method gets a new parameter and it, along with its dependency from A are highlighted red

Then it gets weird.

Coupling tends to travel along lines of dependency but it is not transitive and can "jump" from one place to another without any dependencies in between.

Continuing our example, more than likely a change to the parameters required by class C will necessitate a change to both A and B.

An additional parameter on one of C's methods causes a cascading sequence of changes leading to A

However, that is not necessarily true. B could be encapsulating C and just happen to pass along certain parameters as a matter of convenience, for instance.

A change to C's methods stops with B, so A is not affected.

Likewise, imagine two other classes: M and N. M has no explicit connection, either direct or indirect to N. However, the design of M makes certain assumptions about side-effects created by N. In this case, M is coupled the side-effect created by N and thus to N, itself.

Three classes, M, N, and O as described above.

Attending to dependencies is a good start but there are some deeper concepts that help you manage your coupling in a valuable way. Specifically, all coupling should be intentional, explicit, and needful. You may not be able to hit that target every time but you probably should strive to get there whenever you can.