Visual Basic

Tip 17: Use automated testing tools.

See Chapter 9, ""Well, at Least It Compiled OK!"" for coverage of this broad and very important subject.

Tip 18: Consider error values.

Let's suppose you still want to return an indication of success from a function (instead of using exceptions). What values would you use to indicate whether or not something worked?

Normally, 0 (or False) is returned for failure, and -1 (True) for success. What are the alternatives? Some programmers like to return 0 for success and some other value for failure-the reason for failure is encoded in the value being returned. Other programmers prefer to return a negative value for failure that again encodes the reason.

By using the first alternative, we can quickly come up with some pretty weird-looking code:

If CreateThing() <> True Then ' It worked!

or

If Not CreateThing() Then ' It worked!

or

If CreateThing() = False Then ' It worked!

or

If CreateThing() = SUCCESS Then ' It worked!

SUCCESS, of course, is defined as 0. To capture failure, you can't just do the same, though:

If Not CreateThing() Then ' It worked!
  Else
      ' Failed!
      ' What do we do?
  End If

Here the reason for failure is lost. We need to hold it in some variable:

nResult = CreateThing()
  If nResult <> SUCCESS Then
      ' Failed!
      ' What do we do?
  End If

All very messy, especially where the language lacks the ability to do an assignment in a conditional expression (as is the case in Visual Basic and is not the case in C).

Consider someone writing the test using implicit expression evaluation:

If CreateThing() Then

If CreateThing works, it returns 0, which causes the conditional not to execute any code in the body of the compound statement. Yikes! Imagine what code fails to execute all because someone forgot to test against SUCCESS.

Because any nonzero value is evaluated as True (in an If), using a value other than 0 (say, a negative value) to indicate failure can be equally dangerous. Given that in any conditional expression you don't have to test against an explicit value and that nonzero means execute the compound statement, the language conspires against you here not to use 0 as a code indicating success.

I'd advise sticking to True meaning success and False meaning failure. In the case of failure, I'd implement a mechanism such as the one used in C (errno) or perhaps Win32's GetLastError. The latter returns the value of the last error (easily implemented in a project-you could even add a history feature or automatic logging of errors).