Wednesday, June 13, 2012

Read me if you can

In my starting days of coding I had a notion if you don't understand the code means its a tough program, some hi-fi advanced code. And if the code compile with out error and execute properly means its perfect in all aspect.
My first programming language was C. There was a lab exam where we need to code 5 given program. I had completed well ahead of time, all the five were compiling and running properly. The teacher was checking each student's program and evaluating. You have to get minimum three programs right to clear the exam. The teacher came to me he read one by one program. He had checked 4 programs and found all are correct. Fifth one he saw the code, in first look he didn't get the logic he told its incorrect with out compiling or executing. Before I could explain back he had already deleted the source folders. I was bit upset because I knew I got five out of five correct. But it was recorded 4.  I was thinking I didn't get 5 out 5 just because some body was not able to read it.
And after I started working in real time project, I understand 90% time you will be working around the codes not written by you. And some point of time some one else will be working on your code for sure. And there is some figure floated on internet, as 80% effort goes in to understanding others code. All these made the point clear codes need to be written such a way that another person can understand it well. And sometime people prefer simpler algorithm instead a complicated one.
There are different best practices in line with various programming language. I found few points which help
1) Naming Convention
name of the variable and method  revel lots of information. for ex :
if ( authenticate(userName,password)
It clearly understood that we are authenticating by passing user name and password.
2) Comments
We all know we need to write comments. I feel Class label comments, method label comments are always handy. It should always tell more than code. I mean certainly by seeing code we get some idea, and comments should add some thing to it. For ex:
/* Check for  Ldap authentication */

if ( authenticate(userName,password)
In this case comments add some more info to the picture.
It is always nice to add few line of comments for a particular block of code.
3)  Use of parenthesis while doing logical operation.
parentheses always make easy to understand complex logical expression.

And the list goes on. You also can share some of the ideas here which helps understand the code. If the code is well understood it adds lots of value. And programmer can happily understand it and work with it. Happy Programmers always do wonderful things. ;)