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:
- BE FEARLESS.
- Compile early and often.
- Consult the documentation (RTFM).
- Use descriptive variable names.
- Comment liberally, including every function, its parameters, and return value.
- User interface should be at the top-level only. Computational functions don’t talk to the user.
- Use print statements to debug.
- No global variables.
- Organize your code into functions. Avoid repetition.
- 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!