Sunday, November 3, 2013

Code Guidelines

A list of basic goals for creating code.

In our team project at work, we wanted to have a set of style guidelines to allow everyone to more easily and quickly read the codebase and to avoid spurious code reformatting changes. As you might expect, there were different opinions on many points. To avoid fruitless "my way is just better" discussions, I wanted to step back and make sure we could all agree on some general goals. With that agreement in place, we could at least ask people to explain how their preferred style on some point supports our general goals. If nobody can provide an argument to support a favored construct, we might as well flip a coin.

Below are the goals I proposed and with which the team agreed. I think many of these are obvious, but then I usually believe in stating the obvious. The first two criteria below are also listed in my post on Software Quality Dimensions. Your team may choose slightly different guiding principles, but I think having the team agree on and write down their principles and asking people to justify their proposed standards against those principles can help short-circuit disagreements that might otherwise take longer to resolve.


In order of priority, with the most important criteria first: First, we want our code to be correct.
This means that the code must:
  • perform the desired primary behavior.
  • behave in a defined way for expected error conditions.
  • not have undesirable side-effects.
  • not have security vulnerabilities such as buffer overflows or injections.
  • not have memory problems such as leaks or use of released or uninitialized memory.
  • run fast enough for the intended use cases (but without premature optimization).
Second, we want our code to be robust.
This means that the code should be written in such a way as to minimize the probability of incorrect behavior under a wide range of conditions, including when:
  • it receives unexpected, corrupted, or no input data (graceful degradation).
  • a programmer unfamiliar with the code makes changes to it.
  • the functionality of neighboring code changes.
  • the development environment or toolset changes.
Third, we want our developers to be as productive as possible.
This means the code should be written such that:
  • developers are unlikely to misunderstand what the code does (principle of least surprise).
  • developers can read and understand the code quickly.

No comments: