Guard pattern

Tags
If
Summary

Prevent your code from doing something crazy.

Situation

Your program could do something stupid, like try to divide by zero.

Needs

Some data to test.

Provides

Usually an error message.

Action

Use an If statement, like this:

  • sApples = InputBox("How many apples?")
  • sGoats = InputBox("How many goats?")
  • ' Guard against goatlessness.
  • If sGoats = 0 Then
  •     MsgBox "Goatlessness detected. Nobody gets apples."
  • Else
  •     sApplesPerGoat = sApples / sGoats
  •     MsgBox sApplesPerGoat & " apples per goat"
  • End If