top of page

Comments Should Say Why, Not What or How

Comments can be great in code, but there's oftentimes some confusion on when comments are worthwhile. They don't come for free. Writing comments takes time, and keeping them up to date does as well. Not to mention, outdated comments can sometimes be more of hinderance than having no comments at all.


I prefer comments that explain why you're doing something, not what you're doing


What Comments

Often times when learning to code or reading about comments, you'll see comments like the one below.

user.delete() // Delete the user

This is an example of a comment that doesn't tell you any more than the code itself does.


Why Comments

Sometimes your code does weird stuff. You're working on a legacy system, you have a deadline that forces you to cut corners, or there's a strange quirk with an API you're using. In these cases your comments that explain why you're doing something will help future developers.


Sometimes when working others' code, or your own old code, something can look wrong. You might want to change it. But there's a chance it's not wrong, just really weird.


Let's look at an example.

function destroyUser (user, reason) {
    addLog('Deleting ' + user.id + ' because ' + reason)
    user.archive()
    user.destroy()
}

At first glance, this code appears wrong to me. Why would you archive something if you're just going to destroy it immediately afterwards? I might be tempted to remove that line to clean up the code some.

function destroyUser (user, reason) {
    addLog('Deleting ' + user.id + ' because ' + reason)
    // A legacy rule in our database prevents us destroy users who aren't
    // archived. This is because of some old auditing scripts that get
    // run every month.
    user.archive()
    user.destroy()
}

This comment might not be perfect, and the code might not be perfect. Hell, you could argue that it's lazy to not just fix those auditing scripts! That may be true, but right not they aren't fixed, so you can't remove the archive call, so this comment is worth it.


Your comments should answer questions that future developers might have. Nobody is wondering what blogPost.setPublishedToNow() is doing, so it doesn't need a comment.


Thanks for reading. I'm Colin Kierans I approve this post that I wrote.

bottom of page