Brian Kernighan's Programming Style Tips
Here is a summary of the very important programming style tips from
Brian Kernighan's 1994 guest CS50 lecture.
- Say what you mean, simply and directly.
- Use the ``telephone test'' for readability.
- Write clearly - don't be too clever.
- Don't use conditional expressions as a substitute for a logical
- Parenthesize to avoid ambiguity.
- Each time you make a test, do something.
- Follow each decision as closely as possible with its associated action.
- Use the good features of a language; avoid the bad ones.
- Capture regularity in control flow, irregularity in data.
- Each module should do one thing well.
- Make sure comments and code agree.
- Don't just echo the code with comments - make every comment count.
- Don't comment bad code - rewrite it.
- Use symbolic constants for magic numbers.
- Watch out for side effects and order of evaluation.
- Macros are not functions.
- Watch out for off-by-one errors.
- Test programs at their boundaries.
- Program defensively.
- Make sure input cannot violate the limits of the program.
- Make it right before you make it faster.
- Keep it right when you make it faster.
- Don't sacrifice clarity for small gains in ``efficiency.''
- Don't stop with your first draft.
[From The Elements of Programming Style,
Kernighan & Plauger, McGraw-Hill, 1978]
Note: this book is still well worth reading- even though most
of the examples are in languages that you probably haven't heard of,
the principles are universal. -DJE