Programming Style Guidelines
Summary
Dr. Harris
- A poor programming language should never be used as an excuse for writing poor code
- Optimize the programmer, not the program
- A program is like a story, how you say it is as important as what you say
- Comments & indentation are an important part of the story
- Comment the purpose of a module and subroutine
- Good code is self-commenting
- Comments should be accurate, concise, and assume literacy in the program's language
- Make comments standout
- Use blank lines to separate blocks of code
- Use consistent indentation
- Use different indentation for continued statements
- Use indentation on comments as well as code
- Estimates of how long it will take to write a program are usually too small; plan accordingly
- If you do not understand the problem, you cannot design a solution
- In prose or in programming, clarity begins with a well-designed structure
- Re-use
- Think generic
- High cohesion, low coupling
- Make coupling visible
- Replace repetitive code with calls to a function
- Encapsulate
- Given a choice between clarity and length, pick clarity
- If mid-block declarations are needed, the block is probably too long
- Use recursion for recursive data structures
- "Use data arrays to avoid repetitive control sequences."1
- If the code is not clear, it probably could be. Make it so
- Use meaningful identifier names
- Use different naming conventions for different types of identifiers
- Initialize variables just before their use but do not initialize just to initialize
- Use constants
- Declare all variables and constants at start of a block
- Eliminate unused local variables or constants
- Use each variable for only one purpose
- Avoid temporary variables, but when used, two-letter names are ok
- At most, one statement per line
- Parenthesize expressions
- Avoid complex expressions
- Avoid unnecessary loops and branches
- If your code has more than five levels of indentation, you probably need to simplify
- Avoid multiple exits from loops and subroutines
- "Make sure special cases are truly special" 1
- It is not important that a program works with some possible inputs, it is important that it works with any possible inputs
- Floating point values are approximate
- "Watch out for off-by-one errors"1
- Test for valid input
- Program defensively
- Test for valid subroutine argument values
- Use assertions to catch program bugs
- Use asserted default branch
- Listen to compiler warnings
- The objective of debugging is to find bugs, not to prove correctness
- Fix the bug, not just the symptom
- All errors are significant
- Provide useful error messages
1. The Elements of Programming Style, Kernighan and Plauger, 1978.