Chapter 22. Preventing Bugs

Many programmers believe that the way to make a program robust is to make it able to continue running even when it encounters errors. For example, consider the following version of the Factorial function:

' Recursively calculate n!
Private Function Factorial(ByVal n As Long) As Long
    If (n <= 1) Then Return 1
    Return n * Factorial(n - 1)
End Function

This function is robust in the sense that it can handle nonsensical inputs such as −10. The function cannot calculate −10!, but because it doesn't crash you might think this is a safe function.

Unfortunately, while the function doesn't crash on this input, nor does it return a correct result because −10! is not defined. That makes the program continue running even though it has produced an incorrect result.

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 learn how to make bugs jump out so they're easy to fix instead of remaining hidden.

INPUT ASSERTIONS

In Visual Basic programming, an assertion is a statement that the code claims is true. If the statement is false, the program stops running so you can decide whether a bug occurred.

The .NET Framework provides a Debug class that makes checking assertions easy. The Debug class's static Assert method takes as a parameter a Boolean value. If the value is False, Assert stops the program and ...

Get Stephens' Visual Basic® Programming 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.