
Preventing Bugs
Many programmers believe that the way to make a program robust is to make it able to
continue running even if it encounters errors. For example, consider the following version
of the
Factorial method:
// Recursively calculate n!
private long Factorial(long n)
{
if (n <= 1) return 1;
return n * Factorial(n - 1);
}
This method is robust in the sense that it can handle nonsensical inputs such as –10. The function
cannot calculate –10!, but at least it doesn’t crash so you might think this is a safe method.
Unfortunately while the function doesn’t crash on this input, it also doesn’t return a correct
result because –10! is not defined. That makes the program continue running even though it
has produced an incorrect result.
The method also has a problem if its input is greater than 20. In that case, the result is too
big to fit in the
long data type so the calculations cause an integer overflow. By default, the
program silently ignores the error, and the result you get uses whatever bits are left after the
overflow. In this case, the result looks like a large negative number. Again the method doesn’t
crash but it doesn’t return a useful result, either.
In general, bugs that cause a program to crash are a lot easier to find and fix than bugs like
this one that produce incorrect results but continue running.
In this lesson, you learn techniques for detecting and correcting bugs. You ...