14 kwietnia 2012

Comments ? No, thank you...

Dear Programmers ! Please, do not write comments in your code. Seriously. I mean it. In most cases comments are totally useless so what is the point in writing them ?

In my career I have seen a lot of comments inside code. Some of them were funny, some of them not. Part of them were even mine. I admit it and I want to apologize for them. I think that every programmer who has created this little bastard called 'comment' in order to make code more readable should apologize to each innocent soul forced to read it.
/** The attempts. */
private int callDuration; 
Why do we write comments ? There are two main reasons for that. First - because we dont know how to write good and clean code. We have trouble expressing algorithms that we have in our minds. Second - because we are writing code in a hurry and we believe that we will refactor later. Later doesn't exist. Every time we have a thought that it would be better to comment this piece of code we should know that our code sucks as hell.
/** The ftp statistics. */
 private HttpStatisticsWithMonitor httpStats;
Commenting code in order to make it more readable is almost always a bad idea. Instead of that we should spend a while thinking how we can improve our code. Steve McConnell said that "Good code is its own best documentation." and I think that this is truth that we should all follow.
/** The canceled. */
private boolean canceled;
Ok, but whats wrong with comments ? Well, there is a problem with them. It is quite easy to make comments out of date. When programmers are making refactoring he is changing code and almost always forget about updating comments. This is normal situation, everyone does this. We care about the code, not about comments. Code is the true value of our software. After a few refactorings comments and code begin to be totally unrelated. Comments that are not related to the code don't give you any benefits. Whats more they become an element of distraction and they make hard programmers life even harder.
Account account = accountsContainer.getAccount(number);
// check if account is a premium type which means  
// contains more then 2000 value 
// and it exists for more then 1 year
if(account.getBalance() > 10000 && 
   DateUtils.differenceBetweenDatesInDays( 
   account.getCreationDate(), new Date()) > 365 ){
...
}
At the end I just want to say that not all comments are bad. There are some cases when comments are necessary. For example comments about license or with information about some law stuff. But that are just exceptions! Every time our minds tell us that we should write some comment to explain a mechanism that we have just implemented we should say "Comment ?! No, thank you... I must improve this code !".

1 komentarz: