Programming Tips and Advice

A collection of miscellaneous programming tips. Mostly aimed at beginner or intermediate programmers, but even the best of programmers need a reminder sometimes.

  1. Keep it simple, stupid.
    • Program exactly what you mean, and optimize later. (But don’t write lazy slow code on the first run either!)
    • Don’t use language features just because they exist (e.g. C++ templates).
  2. Use the right tool for the job, and be willing to learn new tools as the job requires. Be flexible.
    • Python is best for gluing other stuff together, and getting something up and running quickly.
    • C++ can be do, or be used for, pretty much anything. This is not always a good thing.
  3. Learn C. No way around it.
  4. Learn the const keyword, in all its incarnations, and use it wherever possible.
    • Pass by const reference for anything significantly larger than a word (usually 64 bits).
    • Declare class functions const as appropriate. If this causes a lot of compiler errors, you’re doing something wrong.
  5. Test thoroughly. Testing is what demarcates engineering and scratch work.
  6. Learn the Linux toolchain and other tools. Even just a few tricks with gcc, bash, git, gdb, valgrind et al. can go a long ways. Especially git.
    • Use Linux as a daily OS – I recommend Ubuntu or Pop_OS. It’s actually easier to get things done in Ubuntu than in Windows nowadays.
  7. Ensure a bijection exists between calls to malloc/calloc/new and calls to free/delete.
    • Write the allocation, write the deallocation immediately after, then write your code in between those lines.
    • Also, make sure the correct number of bytes (hint: use sizeof) are argued to malloc/calloc, and check the returned pointer.
  8. Write functions to return error codes, and check those returned values.
  9. Use preprocessor macros to create a debug build.
    • The tougher the task, the more assertions you should have – 1:8 was the recommended ratio of assertions to lines of code for my undergraduate operating systems course.
    • Also, macros are a must-know for any cross-platform programming.
  10. Have a complete and clear specification for the project, and do not try to add in features a week before the deadline.
    • Start the project when it is assigned, and don’t procrastinate, unless you want to have a segfault you can’t figure out on the due date.
  11. Only keep one copy of a program installed on your system.
    • Python is the worst offender, but the 2/3 split isn’t always easily resolved.
  12. Never hardcode values – it makes debugging harder, and makes bugs easy. Use static const (C++) or #define (C) for constants.