Programming Style Guidelines
Summary

Dr. Harris

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