Monday, December 04, 2006

Programming style


Programming style is a term used to describe the effort a programmer should take to make his or her code easy to read and easy to understand. No two programmers write the code identically, so the way to name variables, to structure the logic, or to organize the code has to follow a certain logic.
Here are styles and conventions to help any reader to understand what the program does and why.

Minimize the number of lines of Code.
Minimize the number of variables - localize as much as possible.
Minimize the number of routines - localize as much as possible.
Modules are free standing and have a specific objective. Just keep everything simple. The fewer of anything you have in your code, the easier it is to reuse, maintain, and enhance.

Give your variables, functions, and types self-explanatory names easy to understand for everybody (including you). Make sure it's not the same as a program command. Calling them i and j is short, and easy to type, but hard to debug.

Indent your code to make it legible. It will help you to see the blocks of the program easily. You can use whatever spacing looks good to you, but indent at least 2 spaces.

Comment your code liberally. If your program can be broken down easily into stages, comment each stage. If you have defined your own functions or datatypes, comment them extensively, explaining what they do, and what they're for. If you come up with an implementation that's in any way obscure, cute, or hacked, comment it well. You may want to use the same trick again someday, and it's helpful to know how it worked.

The Elements of Programming Style

1. Say what you mean, simply and directly.
2. Write clearly - don't be too clever.
3. Don't use conditional expressions as a substitute for a logical expression.
4. Parenthesize to avoid ambiguity.
5. Follow each decision as closely as possible with its associated action.
6. Use the good features of a language; avoid the bad ones.
7. Each module should do one thing well.
8. Make sure comments and code agree.
9. Don't just echo the code with comments - make every comment count.
10. Don't comment bad code - rewrite it.
11. Use symbolic constants for magic numbers.
12. Watch out for side effects and order of evaluation.
13. Macros are not functions.
14. Watch out for off-by-one errors.
15. Test programs at their boundaries.
16. Program defensively.
17. Make sure input cannot violate the limits of the program.
18. Make it right before you make it faster.
19. Keep it right when you make it faster.
20. Don't sacrifice clarity for small gains in efficiency.
21. Don't stop with your first draft.

No comments: