Coding Standards

Coding standards are just one part of a programmer’s toolbox. In many cases, coding standards are forced on the programmer “because that’s the way we do things here”, but having standards can be extremely useful, beyond getting a passing grade for following what your professor wants.

In my view, coding standards should accomplish 3 goals – first and foremost, they should make code more readable. This is extremely important, since other people will be reading what you create if you’re working with a team size of larger than one. As long as the team is following its own coding standards, this is more or less a given result of the standards.

As a supporting goal, coding standards should help you write better code. The compiler is there for more than just creating your executable from code you create, after all. It does a variety of error checking and prevention for you, which you should take advantage of. There are a few specific cases of this which I have integrated into my own C++ standards, such as:
* When possible, put contants before variables in if statements. That is, “if (0 == x)” is better than “if (x == 0)”, because if you accidentally use = instead of == in C++, “if (0 = x”) will report a compiler error, which warns you that you may have made a mistake. “if (x = 0)” compiles just fine, and will always pass into the if statement, which is probably not what you want.
* Use const correctness. If at all possible, make class functions const, and pass parameters as const, so that if you do change something when you don’t mean to, the compiler warns you.
* Use { }, even for single line code blocks. If you add additional lines to the block, everything still works properly, and it adds some space to the code. I’d rather have more space, so long as it gives me more readable code.

The final major code of coding standards should be to assist you in writing efficient code whenever possible. Again, C++ examples:
* Use const correctness. This can give clues to the compiler about what you plan on not changing, so it can avoid cache stores to main memory, or register stores to cache.
* Use pre-increment (++i) instead of post-increment (i++). In C++, you can overload operators, and the post-increment operator can be slower in many cases than pre-increment, because it creates temp variables, uses copy constructors, and other operations which pre-increment avoids.

There are countless other examples of why coding standards can be useful to you and your team. These examples aren’t perfect, but they are a starting point. Having a reason for what you do is most important, though, since it will help make your code make logical sense later.