James Fulford
2 min readMay 21, 2020

--

Good question. I didn’t make this clear when I wrote this article. I have 3 principles at play here.

The first principle at play is “things that are related should be near each other”, which is a part of maintainability. By writing the cancel logic right next to the setup logic, I avoid the spaghetti code problem with more complex use-cases (specifically, where the cancel logic changes at different points in the promise executor).

The alternative is to define all the cancellation logic in one place (ahead of time) and all the setup logic in another, then force future engineers to keep the two in sync. This won’t happen, because the cancelation code can get complicated fast, and ain’t nobody got time for that.

The second principle is extensibility. This code may count to 10, but its purpose is to be copied as a pattern for others. Others may have more complex use cases, so I wanted to set the right pattern for them to follow, instead of writing the minimal pattern needed for hide-and-seek :). Other use cases may need to override the cancel behavior multiple times during execution. Doing it this way nudges the code-copier how to handle the next stage in their cancellable effect.

The third principle here is “avoid let, reassignments, and asynchronous logic”, because this quickly becomes complex, therefore buggy, therefore a maintainability hazard. Suppose we didn’t define a new cancel function after setup. The alternative is to define the cancel function before our custom logic and not overwrite the cancel function. Here’s the catch: our custom logic often produces something needed for cancellation (like id above, but could be a callback or an RxJS Subscription in other scenarios). You could assign this value to a pre-defined let , but now your cancel logic needs to check if that let variable is not undefined. And if you need to ‘proxy’ assign yet another value? Another let, another conditional? Now you have to consider 4 scenarios (defined and undefined for each variable; the # of scenarios grows exponentially). Why not just have 1 let and assign the logic directly, avoiding the exponential if ‘s entirely?

Again, good question.

--

--

James Fulford
James Fulford

No responses yet