Trade-off time.
One problem with substituting >= for == is that you can mask catastrophic failures.
Murphy being omnipresent, it is possible for an otherwise incremented-by-one variable to suddenly take on an outrageous value. This happens more often by errant maintenance changes or some obscure code path than by cosmic rays. If that happens, you probably want to halt the program, rather than quietly ignoring the problem and going on.
This begs the question of whether it is worth adding extra sanity checking code before every reference to a variable. Maybe so, usually not. Some kinds of catestrophic failures are so catestrophic that you're going to blow up in short order anyway. And the extra code overhead can be a hit on performance.
In some languages, this kind of defensive programming is done a conditionally compiled ASSERT mechanism, which can be turned off during deployment. Writing
covers both the case of a normal fuse burning down and the abnormal event of the fuse suddenly going out of range.ASSERT(0 < $count && $count <= 10); last if $count == 10;
I often do this when writing complicated logic in classes, where an object's instance variables (or Perl equivalent) can possibly be side-effected by an intervening method call. (Someone once thanked me for being defensive two years after I left a company. They'd being doing maintenace work to extend some stuff I'd done, and ASSERT code kept them out of trouble.)
In Perl, I'll sometimes add asserts during development, then comment them out when the code is stable. E.g., #die "assert" unless @{$p->{'children'}} > 0; This doubles a "real" comment.
In reply to Re: Defensive Programming
by dws
in thread Defensive Programming
by George_Sherston
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |