10 Coding Principles, by Greg Landweber

My undergraduate mentor in the math department, Prof. Greg Landweber, taught me his 10 coding principles in a computational methods tutorial. They’ve gotten me through my BA project, MSc thesis, and I’m still using them in my PhD. They are as follows:

  2. Compile early and often.
  3. Consult the documentation (RTFM).
  4. Use descriptive variable names.
  5. Comment liberally, including every function, its parameters, and return value.
  6. User interface should be at the top-level only. Computational functions don’t talk to the user.
  7. Use print statements to debug.
  8. No global variables.
  9. Organize your code into functions. Avoid repetition.
  10. Think about algorithms. Avoid checking every possibility by brute force.

Number 1 is my favourite. Number 10 is still something I’m working on. I forced myself to use these principles when I was learning to code, and I think they make me a better programmer than I’d be without having learned and used them. One idea I would add, which is a principle of both good coding practice and laziness:

    11. If you’re manually doing a task often, automate it. You will be rewarded handsomely for your effort up-front.

What are your coding principles?

EDIT: This post generated some great discussions! Here are some suggestions and addenda from my friends and colleagues:

    3a. Write documentation in the first place, and update it as the code grows and changes.
    11a. If you have to do it twice, automate it!
    12. Think before you code. (As it was pointed out, “think before you X” is a good rule of thumb for life.)
    13. Use assertions to debug.
    14. Use version control (e.g. Git).
    14a. Never commit broken code.
    15. Avoid archaic languages (fortran, IDL) whenever possible.
    16. If any code unit has more than ~50 lines (pick a relevant threshold), it needs to be split into separate units.
    17. Write test cases for your code.
    18. Just because you’ve found a bug doesn’t mean you’ve found all the bugs and your code works now.
    19. Don’t just be prepared for failure, expect it! There will be a problem with the code you’re writing right now, but you’ll be able to fix it eventually!