Monday, June 27, 2005

Comments are deodorant for code

"Code smell" is the rather evocative term used to describe an aspect of a piece of code that indicate a fundamental problem with the current design. Comments are frequently used to explain what is going on in complex code. Therefore they act like deodorant on smelly code.

Most comments I read in code are totally pointless. 'print "hello"; // this line prints hello' or worse 'print "goodbye"; // This line prints hello'. Another common use is as follows...
void someMethod()
//add a new user
... Code to add the new user ...
// give the user a new password
... Code to give the user a new password ...


What you have here are a whole bunch of methods all tied together. My money is that if you look elsewhere in the code you will find another method that also implements the 'add new user' code too. Methods like this make duplication much harder to spot.

Code should be self explanatory. If you have to put a comment in the code to explain some aspect of its behavior then the code is not clear enough.

There are three things you are trying to get across to the reader of your code:
1/ What is it doing?
3/ How is it doing it?
2/ Why is it doing it?

Here is how to address each of these concerns.

What is it doing?
The name of the method answers this question.

How is it doing it?
The body of the method should be an easy to read list of steps.

Very occasionally reading the 'How' of a method will leave you wondering 'why is it done this way? Usually this is time to refactor. Sometimes, however, this is not the case. Maybe the operations are order dependent or apparently superfluous steps are required for someone API to work correctly. Explaining these situations is what comments are for. It is also a good idea to have unit tests to verify these conditions remain true.

Situations where comments are require should be rare!

So... Next time you are adding a comment to explain some code, ask yourself the question "Is this comment explaining What? Why? or How?" if its not "why?" then it shouldn't be a comment!

No comments:

GitHub Projects