Creative Commons License Copyright © Michael Richmond. This work is licensed under a Creative Commons License.

Programming Style

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]

Let me add a few suggestions of my own:

  1. As you write a program, imagine yourself coming back to work on it again three years from now. Make sure that your future self will understand it.

  2. In most cases, efficiency is MUCH less important than clarity. Computers get faster every year, but people don't get any smarter.


Some examples for you to ponder:

Some suggested references -- not specific to MATLAB

Some suggested books:


Creative Commons License Copyright © Michael Richmond. This work is licensed under a Creative Commons License.