Skip to content

Comment your code

April 17, 2017

Commenting the code is unnecessary unless your code is really bullshit. I mean you do not need to paraphrase your code. This is really loosing time and efoort. But there is some tips you should ALWAYS follow.

 * Set the height.
public void setHeight(int height){
  this.height = height;

Above, we have a not documented code. The comment is simply useless. But we need more information.

I suppose the method is included in a class named Person. This is the weight of the person. But we don’t know more. The coreect cooment is the following:

 * Set the height in centimeters. A value of 0 (zero)
* means the information is missing.
public void setHeight(int height){
  this.height = height;

Now, you have a comment with a real added value. I think you understood the underlying principle: the comment must be an added value to your code. Your code (at least this part) does not give information about the expected value. But the comment give this information.

Basically, each time you write a comment, you just have to be sure you have:

  • the values accepted (here, it is implicit that negative values are not possible) and mainly those which are “limit”.
  • Explicit if null values are accepted (or not).
  • For returned value, explicit if the value returned can be null or not.
  • Explicit all special cases (the weight of zero means unknown).
  • Do not forget to specify the unit of the value (meters, centimeters, kilograms, bytes, seconds, milliseconds). This is really important and not easy to track.

Do the effort. And your coworkers (even yourself in several weeks) will be happy,

For classes, I like to have examples of usage. Just copy and paste a example and put it in the comment (in javadoc, use <pre> tags). This is far more interesting than any theorical explanation.

Sometime, it helps to give the role of the method and when to use and when not to use it. Give alternatives when possible (sometimes, you have methods that does more or less the same then explicit them).

This simple advice should help a lot in creating good code.


From → Coding

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: