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.
  1. Say what you mean, simply and directly.

  2. Use the ``telephone test'' for readability.

  3. Write clearly - don't be too clever.

  4. Don't use conditional expressions as a substitute for a logical expression.

  5. Parenthesize to avoid ambiguity.

  6. Each time you make a test, do something.

  7. Follow each decision as closely as possible with its associated action.

  8. Use the good features of a language; avoid the bad ones.

  9. Capture regularity in control flow, irregularity in data.

  10. Each module should do one thing well.

  11. Make sure comments and code agree.

  12. Don't just echo the code with comments - make every comment count.

  13. Don't comment bad code - rewrite it.

  14. Use symbolic constants for magic numbers.

  15. Watch out for side effects and order of evaluation.

  16. Macros are not functions.

  17. Watch out for off-by-one errors.

  18. Test programs at their boundaries.

  19. Program defensively.

  20. Make sure input cannot violate the limits of the program.

  21. Make it right before you make it faster.

  22. Keep it right when you make it faster.

  23. Don't sacrifice clarity for small gains in ``efficiency.''

  24. 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