Numbers in General
1. Avoid "magic numbers".
2. Use hard-coded 0s and 1s if you need to.
3. Anticipate divide-by-zero errors.
4. Make type conversions obvious.
5. Avoid mixed-type comparisons.
Integer
1. Check for integer division.
In the real world 10*(7/10)=(10*7)/10 is true, but not in the world of integer arithmetic.
2. Check for integer overflow.
3. Check for overflow in intermediate results.
int A=1000000
int B=1000000
int C=A*B/1000000
In fact, C is -727
Floating-Point Numbers
1. Avoid additions and subtractions on numbers that have greatly different magnitudes
2. Avoid equality comparisons.
3. Anticipate rounding errors.
Characters and Strings
1. Avoid magic characters and string.
2. Watch for off-by-one errors
3. Know how your language and environment support Unicode.
4. Decide on an internationalization/localization strategy early in the lifetime of a program.
5. If you know you only need to support a single alphabetic language, consider using an ISO 8859 character set.
6. Decide on a consistent conversion strategy among string types.
Boolean Variables
1. Use boolean variables to document your program.
2. Use boolean variables to simplify complicated tests.
Samples in P12
Enumerated Types
1. Use enumerated types for readable.
2. Use enumerated types for reliability.
3. Use enumerated types for modifiability.
4. Check for invalid values.
Named constants
1. Use named constants in data declarations.
2. Avoid literals, even "safe" ones.
3. Use named constants consistently.
Arrays
1. Make sure that all array indexes are within the bounds of the array.
2. Thing of arrays as sequential structures.
3. check the end points of arrays.
4. If an array is multidimensional, make sure it's subscripts are used in the correct order.
5. Watch out for index cross talk.
6. Throw in an extra element at the end of an array.
博客介绍了编程中各类数值和数据类型的使用要点。包括避免使用“魔法数字”,检查整数除法和溢出,避免浮点数的不当运算和比较,注意字符和字符串的国际化,合理使用布尔变量、枚举类型、命名常量,以及确保数组索引在范围内等。
937

被折叠的 条评论
为什么被折叠?



