WCF#8: Untangle Spaghetti Code With This Simple, But Old,Technique
Breaking code down into self-contained chunks that respond to events sounds difficult. It needn’t be…
We’ve all done it. We’ve added just one wafer-thin extra if
statement to an already deeply nested mess of code. Or we’ve added just one more flag to make something work in some unexpected situation. Or we’ve copied code to handle a certain event to each of the places that event can occur.
Of course we regret it.
Non, je ne regrette rien.
Edith Piaf, world’s worst programmer
It turns out that a simple technique can be used to untangle all this code, separating the what-to-do from the when-to-do-it. The trick is to think about programming a little differently, and move from code-as-driver to code-as-passenger.
Code as driver
We’ve all be taught that when we program, we’re telling the computer what to do. That leads us to think of our programs being in control of what’s happening. We design our code in sequential chunks, where each chunk steps from statement to statement to statement. Being in control like that feels natural, so we tend to try to make these chunks as big as possible, because then we can control what they do as much…