Freigeben über


Safety by Accident

The oxymoron "safety by accident" came up in a conversation. It sounded very natural in context when we first mentioned it, and then we stopped for a second and realized it was kind of silly. The idea was that some code was flawed, but some unrelated thing just so happened to conveniently prevented the bug.

Some examples:

  1. When 2 bugs nullify each other. Fixing one bug may thus expose the other.  This could happen with 2 off-by-one bugs canceling each other out; or perhaps a double-negative; or if a function returns the wrong value but nobody checks the return value.
  2. Code uses an undefined (or uninitalized) variable which conveniently happens to have a workable value.
  3. When a buggy codepath is avoided by some other unrelated check.

Code like this can be a maintenance nightmare; because while the behavior may be technically correct for current usage patterns, it's very brittle as usage patterns change.

 

Here's a simple example of 2 bugs nullifying each other:

         static bool IsPositive(int x)
        {
            return x < 0; // bug #1, wrong check
        }
        static bool IsPositive(string s)
        {
            int x = -int.Parse(s); // Bug #2, parse gives inverted value.
            return IsPositive(x);
        }