Thursday, September 6, 2018

For Coupling, Ask "How Intentional Is This Dependency?"

Coupling needs to be controlled. One way to do that is to evaluate whether or not any given instance of coupling is viable.

Today's code quality question is this: "How intentional is this dependency?"

Note, it's not about how intentional the dependency looks. It's about whether a dependency actually is something you meant to put in place or just an accidental tag-along from what you really wanted to use.

Consider this design...



Here we have coupling from something that is supposed to draw borders around the edge of a picture to a class that is responsible for building the rendering surface on which that picture will be drawn. In order to get the dimensions of the box, it uses the builder object that created the rendering surface, then draws four lines on the surface.

Something like this is likely to be a matter of convenience. The builder was handy. It happened to contain the required dimensions. So the person building the system decided to pass the builder along rather than doing something else.

What else might have been done?

In this design, the builder is configured from a parameters object, which also has the dimensions. If you absolutely had to choose between coupling the border drawer to the rendering surface builder or the overarching parameters governing the rendering operation, which would you choose?

Congratulations. If you answered "the parameters of the operation", you were correct.



A parameters object typically contains the true semantic specification of what must be done. The builder object is a transient utility and only contains those values because that's how it collects its arguments, through properties.

The coupling to the builder is an accident resulting from what classes happened to be most visible at the time. Coupling to parameters far-better expresses the intention of the coupling.

This kind of analysis can be applied any time you have coupling in a system. It is especially useful for the links that don't make a lot of sense to you or in the places where there are a lot of connections.

At those times, you can ask yourself "How intentional is this dependency?"