Sunday, December 30, 2007

Good Programming Style


Write Clearly - don't be too clever - don't sacrifice clarity for efficiency.
Say what you mean, simply and directly.
Be sparing with temporary variables.
Parenthesize to avoid ambiguity.
Use library functions.
Replace repetitive expressions by calls to a common function.
Choose variable names that won't be confused.
If a logical expression is hard to understand, try transforming it.
Choose a data representation which makes the program simple.
Don't patch bad code - rewrite it.
Write and test a big program in small pieces.
Test input for plausibility and validity.
Identify bad input - recover if possible.
Make sure input doesn't violate the limits of the program.
Terminate input by end-of-file or marker, not by count.
Make input easy to prepare and output self-explanatory.
Make sure all variables are initialized before use.
Watch out for off-by-one errors.
Make sure your program "does nothing" gracefully.
Test programs at their boundary values.
Check some answers by hand.
10.0 times 0.1 is hardly ever 1.0.
Don't compare floating point numbers solely for equality.
Make it right before you make it faster.
Make it fail-safe before you make it faster.
Make it clear before you make it faster.
To make it faster, change the algorithm not small details in the code.
Actually test code to see how fast it is.
Make sure comments and code agree.
Use variable names that mean something.
Format a program to help the reader understand it.
Don't just echo code in comments - make every comment meaningful.
Document your data structures.
Don't over comment.
Don't comment bad code - rewite it.
Use recursive procedures for recursively defined data structures.
Use data arrays to avoid repetitive control sequences.
From: The Elements of Programming Style, Brian Kernighan and P. J. Plauger,McGraw-Hill Book Company, New York, 1974.

No comments: