Stay tuned for an Important Message from The Code Nazi....
I think it's time we increased awareness of our use of control structures! Here is my cartoonish attempt to make everyone more aware of how they use if statements:
As you know, p and q are our old friends from Probability Theory. In the realm of if, our friend p is the probability we will reach the if branch, and our other friend (portrayed as El Diablo in the comic) q is the probability we will reach the else branch.
Now, some programmers, who really suck by-the-by, practice what I call the Optimistic Programming Model. This is a delusional dream-world where no remote resource is ever unavailable, there is no network latency, disk space and memory are unbounded, and nothing else runs on the user's platform but your stuff.
You can easily identify this style by a distinct lack of tests for API failure coupled with a typical lack of exception handling to scope errors, when problems arise (and they do).
The user's experience with this style of system is rarely satisfying, as the system is extremely brittle, sensitive to the smallest perturbation in its environment.
My ultimate anecdote of this goes way back to a previous job in a different century, where everything was in PDP-11 assembly, and we also wrote the OS as well. Somewhere in the system, someone decided that execution would never get here (there was even a comment to that effect), and programmed a HALT instruction.
In our system, a HALT would dump the CPU right to the debug console ODT and its delightful @ prompt.
This wouldn't hurt so bad, except we were running a factory automation supervisory control platform. You know execution found its way to that location eventually.
For extra credit, calculate the number of pissed-off plant management personnel the execution of that instruction generated.
See this blog post for an analysis of someone's work in this field. Yes folks, CreateWindow() can fail.
Hey, didn't you say "Else-less If Kills You Stiff"?
I did. Good thing we have TDD and coverage analysis tools, for those smart enough to use them.
The really bad part is we rarely know even estimates of our friends p and q! By ignoring one branch of the decision, you are ignoring an untold percentage of problems that are the responsibility of that branch, whether you did it wrong or ignored it completely!
This leads to the polar opposite programming model, the Pessimistic Programming Model, where everything that can fail is treated like it will fail, return values are accounted for, and every if has its else. This alone can relieve some level of exception handling, because you covered your probabilities completely.
Just remember, if you think "it will never get here" you are wrong. It will find its way there, just when you are ready to leave on vacation....
No comments:
Post a Comment