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.
- 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
expression.
- 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]
Let me add a few suggestions of my own:
- 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.
- 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:
- Elements of Programming Style, by Kernighan and Plauger.
- Programming Pearls and
More Programming Pearls: Confessions of a coder,
by Jon Bently.
- Code Complete, by Steve McConnell.
- Writing Solid Code, by Steve Maguire.
Copyright © Michael Richmond.
This work is licensed under a Creative Commons License.