Wednesday, September 8, 2010

Coding Standards

Let’s start with the very basic, the coding standards. You don’t find them in a lot of programming books but believe it or not coding standards go a long way in improving your coding efficiency. It’s always better to develop good habits early than try and correct them later like I did. Coding standards are very easy to ignore as they don’t seem to hold any practical value, but if brought into practice can save you a lot of time in debugging and can make your code much more readable.

1. Naming those variables.

Spend a little time in naming your variables. These variables will be littered all over your code, and if you name them intelligently they can help make your code more readable. Not only does “int loopCounter” manages to convey its purpose in a much better way than “ int a”, it helps you keep track of the code when it spans thousands of lines. A number of conventions exist namely camelBack, underscore_notation and the Hungarian notation for naming the variables. The important thing to keep in mind though is to choose one of them and be consistent throughout your code. Do not switch from one notation to the other in a program, it makes the code confusing and difficult to read.

CamelBack int loopCounter

underscore_notation int loop_counter

Hungarian int iLoopCounter

2. Indentation

Indentation again is one of those things which are easy to miss. Indentation makes your code look well structured, easy to understand and helps in debugging. Indent whenever you start a block of code like a function or an if,else,while,for etc.

3. Comments

For a lot of people including me comments are a pain in the A, but make no mistakes they are useful. They come in really handy when you look at your code after a break of a few days. Also, your code will be easier to understand for someone other than you. I have seen people suffering, while having to work with totally uncommented code. Commenting is a good habit and comment as much as you can even at places, where you think they will be useless.

There are a few more of these standards, but these three are the very basic ones. Writing code which is readable and nicely formatted is always a good thing, I hope these standards help you do that.

Happy Coding!
(Thanks to Dylan for giving me these tips and also for making me realize how important these are.)