< Free Open Study > |
Here are several guidelines for making your use of numbers less error-prone: Cross-Reference For more details on using named constants instead of magic numbers, see Section 12.7, "Named Constants," later in this chapter. Avoid "magic numbers" Magic numbers are literal numbers, such as 100 or 47524, that appear in the middle of a program without explanation. If you program in a language that supports named constants, use them instead. If you can't use named constants, use global variables when it's feasible to do so. Avoiding magic numbers yields three advantages:
Use hard-coded 0s and 1s if you need to The values 0 and 1 are used to increment, decrement, and start loops at the first element of an array. The 0 in for i = 0 to CONSTANT do ... is OK, and the 1 in total = total + 1 is OK. A good rule of thumb is that the only literals that should occur in the body of a program are 0 and 1. Any other literals should be replaced with something more descriptive. Anticipate divide-by-zero errors Each time you use the division symbol (/ in most languages), think about whether it's possible for the denominator of the expression to be 0. If the possibility exists, write code to prevent a divide-by-zero error. Make type conversions obvious Make sure that someone reading your code will be aware of it when a conversion between different data types occurs. In C++ you could say y = x + (float) i and in Microsoft Visual Basic you could say y = x + CSng( i ) This practice also helps to ensure that the conversion is the one you want to occur different compilers do different conversions, so you're taking your chances otherwise. Avoid mixed-type comparisons If x is a floating-point number and i is an integer, the test if ( i = x ) then ... Cross-Reference For a variation on this example, see "Avoid equality comparisons" in Section 12.3. is almost guaranteed not to work. By the time the compiler figures out which type it wants to use for the comparison, converts one of the types to the other, does a bunch of rounding, and determines the answer, you'll be lucky if your program runs at all. Do the conversion manually so that the compiler can compare two numbers of the same type and you know exactly what's being compared. Heed your compiler's warnings Many modern compilers tell you when you have different numeric types in the same expression. Pay attention! Every programmer has been asked at one time or another to help someone track down a pesky error, only to find that the compiler had warned about the error all along. Top programmers fix their code to eliminate all compiler warnings. It's easier to let the compiler do the work than to do it yourself. |
< Free Open Study > |