Defensive Programming
You can avoid many common bugs by programming defensively and trying to allow for all eventualities. Here are some guidelines:
Use consistent indentation. We discussed this in the previous section.
 
Use descriptive variable names. Radius1 or Rad1 is easier to understand than S. You might accidentally write TAN(S), but you would immediately see the error in TAN(Radius1).
 
 
Write simple code. The following two code fragments produce identical results. Which is easier to understand?
Fragment 1:
LET P3 (P1 - (PNT_RA O.5*(D2 - D1) ANG(P2 -P1)))
Fragment 2:
LET Shoulder (O.5*(D2 - D1)
LET Angle (ANG(P2 - P1)
LET Vect_S (PNT_RA Shoulder Angle)
LET P3 (P1 - Vect_S)
If there is a bug in any of the previous code fragments, which would you rather debug?
Don't worry about efficient code while you are writing the macro. If your final macro is too slow, then you can concentrate on areas where greater speed may be possible.
Avoid writing long macros. Prefer to use several shorter macros. Each macro can be debugged separately.
 
 
Try to screen out bad user input. We looked at the following code fragment when discussing IF statements:
READ "ENTER 'H' FOR HORIZ, OR 'V' FOR VERT, OR 'P' FOR PERP"
IF (Q='H')
C_LINE HORIZONTAL P2 {if Q='H', only this statement}
{is executed}
ELSE_IF (Q='V')
C_LINE VERTICAL P2 {if Q<>'H', but Q='V', only these}
LET X 3 {two statements are executed}
ELSE
C_LINE PERPENDICULAR P1 P2 {if Q<>'H', and Q<>'V',}
{but Q='P', only this statement is}
{executed}
END_IF
This example is fine for demonstrating IF statements, but not very good for demonstrating defensive programming. What happens if the user accidentally enters, for example, 'Y'? Or enters 'v' instead of 'V'?
Here is a rewritten version, designed to trap accidental user errors:
LOOP
READ STRING "ENTER 'H' FOR HORIZ, OR 'V' FOR
VERT, OR 'P' FOR PERP" Q
EXIT_IF ((Q='H') OR (Q='h') OR (Q='V') OR
(Q='v') OR (Q='P') OR (Q='p'))
END_LOOP

IF ((Q='H') OR (Q='h'))
C_LINE HORIZONTAL P2
ELSE_IF ((Q='V') OR (Q='v'))
C_LINE VERTICAL P2
ELSE
C_LINE PERPENDICULAR P1 P2
END_IF
If your macro fails when the user enters numbers that are too high, too low, or negative, try to trap these numbers with statements such as:
LOOP
READ NUMBER 'Enter number of sides' Num_sides
EXIT_IF ((Num_sides > 0) AND (Num_sides < 20))
END_LOOP
Was this helpful?