img wangjiong

Data Types

发表于2004/10/6 22:36:00  641人阅读

分类: Excerpt of CC2

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.

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.

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.

0 0


取 消