In reviewing the source to express.js I came across a reasonably compact example of temporal coupling.
This is badly factored, and I’ll lay out why:
Temporal coupling is the reliance on a certain sequence of calls or checks to function, rather than having them explicitly called in order in a function. “this, then this, then this have to be called before the state you look at here will be present” is how it works out.
the bits of application.js that call the view are the start of it – the view could be there! Or not! Make one maybe!
That’s reasonably well guarded, because it checks that it’s not there, and sets one up if it’s not already there. But if it was cached previously, and so already set, we’re now dependent on that state, which could have been set in an entirely different way. The only thing that saves us is that the cache is pretty well private.
So now we’ve got temporal coupling between the view’s constructor setting an instance variable and our calling code. This error check is performed synchronously after the construction of the object, which is sad, because that coupling means that any asynchronous looking up of that path is now not available to us without hackery. This is exactly what’s being introduced in Express 5, and so this calling code has to be decoupled.
This is a minor case of temporal coupling, but those pieces of Express know way too much about each other, in ways that make refactoring it more invasive.
There’s a sort of style of programming where the inner components are written first, then the outer ones are written assuming the inner ones are append-only that I think leads to this, a sort of one-way coupling.
Contrast these two places – in the View constructor:
And in the render method:
So now the render method is only safe to call if
this.path is set, and we’re temporally coupled to this sequence:
Without that sequence – instantiate, check for errors, render if good or error if not – it’ll explode, having never validated that
this.path is set..
It’s okay to temporally couple to instantiation in general – it’s not like you can call a method without an instance, not sensibly – but to that error check being required by the outside caller? That’s a terrible convention, and the whole thing would be much better enveloped in a method that spans the whole process – and in this case, an asynchronous one, so that the I/O done validating that the path exists doesn’t have to be synchronous.
So to fix this case, what I would do is to refactor the
render method to include all the checks – move the error handling out of the caller, into render or something called by it. In this case, the
lookup method is a prime candidate, since it’s what determines whether something exists, and the error concerns whether or not it exists.