Writing Good Code Comments

This is a detour from "4 Steps To Be An Effective Engineer".

Let me tell you why writing comments in the code is actually useful and how you should do that.


The main idea is that you should be replaceable.


Yeah, I know how it sounds.
But please, give this idea some time and read the full article.
If you do not trust me, read Passionate Programmer book as well.

Long story short: people tend to leave.

One day you will seize a great opportunity and leave the company.
Or you will go on vacation. Or you will be sick.

And your colleagues will deal with the mess you have created in the codebase...

Why should I write comments?

Quick answer: to make your secret knowledge explicit.

If you do not want your colleagues (or future-you) to suffer, you should note in code all the facts, which force you to make decisions.

This is a kind of knowledge sharing.

Ideally, this should be encoded transparently and simply with the programming language you use. But it is not always possible.

How is that?

Here is an example: you are developing a website and suddenly you have figured out that some evil browser does not let you implement the design of your dream.

But you know a workaround!

And before you start adding dirty things, stop and think:

Are you sure your colleagues know that workaround technique?

And one more question:

Is it obvious, why you have made the decision to make this workaround?

Got the point?

What should I do?

Here is some things you can include in the comments:

  • Note the reason. Why do you need to write those lines of code?
    Do you want to fight a special bug?
    Do you want to optimize for speed?

  • Note the technique. Add a link to the article that describes the technique/workaround you are using.
    If there is no article, just describe the technique with your own words.

  • Refer to the spec or decision. Have you discussed the fix or spec change with your project manager?
    Note this fact to the comment, or refer to the open issue in the tracker.

But it is too cumbersome!

Well, it may seem to be an overkill, if you have not practiced it yet.
But it will save your team from a lot of "WTF?" moments.

And here is one more tip for you:

Write a comment in any place where you (or your teammate) need to stop and think about the code while going through the logic.

Give it some time to settle in your head.

And then, if you are not yet tired, I would suggest you to proceed with the article, explaining how to be efficient.