Tenets of Good Programming

Or “How to Write Code I Would Like.”

  • Be Consistent
    The human mind is excellent at recognizing patterns. Use that to your advantage, write your code in a consistent style. Once your mind is use to it, it becomes much easier to spot syntactical errors at a glance (and possibly other “easy” mistakes).
  • Be Obvious, Be Explicit
    Clever or interesting code may be cute now, but it won’t be for whoever has to look at that code 6 months from now. Funky side effects, unspecified default values - don’t do it.
  • Write Less Code
    Less is more. Fewer lines means fewer bugs. Refactor (or write from the beginning) your code to reduce the number of branches (as long as you are not violating the other tennets). Unit tests and QA resources will exercise the fewer lines and branches of logic better and with greater coverage. It’s easier to get better code coverage with fewer lines of code.
  • Comment About Why
    Not just about what you’re doing. If you’ve followed the above, your code should be pretty straightforward to figure out, right? Sure we figured out that you wrote a bubble sort but we might just want to know why you wrote a bubble sort. Comments that answer “What?” are really only useful when your code is non-obvious. Comments that answer “Why?” will always be useful.
  • Do The Right Thing
    For any problem there are usually a couple of options: 1) Do the right thing. 2) Err.. actually there’s just that one. What is temporary tends to become permanent. Avoid doing half-assed hacks that you’ll regret to maintain. Granted, sometimes the “right thing” is much more time consuming to implement. Then, and only if a simple hack exists, are you allowed to use the hack to temporarily solve the problem. But add the “right thing” to the plan/todo list/schedule. If now simple clean hack exists - forget about it, and go straight to the “right thing”.

Oh and one pet peeve:

  • Reversing the Order of the Comparison Operands
    OK, I can understand why poeple do “5 == a” instead of “a == 5″ (to protect against accidentally writing an assignment versus an equality comparison). However, I really don’t want to see “5 > a” instead of “a < 5". What in the world are you hoping it will protect you from?

I should post this on the company’s wiki. I don’t always follow every rule, but “Do As I Say, Not As I Do”. Hypocrisy allows us to aspire for greater things for others.

Leave a Reply