DEV Community

Jaap Groeneveld
Jaap Groeneveld

Posted on • Updated on

About code comments

Documentation and comments serve a similar purpose. It is about communicating to other developers now, to other developers in the future and also to yourself in the future.

When I am talking about comments, I am not talking about comments used to document an API, functions, classes or modules. These are not really comments but rather inline documentation.

In this Article I am talking about comments but also check out my article on documentation.

Comments

Code comments have a really bad reputation and there is a good reason for it.
Comments, just like documentation, lie really quickly. Most often because they get outdated and are not updated.

Often, they only state the obvious and this just clutters the code.

#loop through the values to be checked
while i <= maxNum:
    [...]
Enter fullscreen mode Exit fullscreen mode

For this reason, a lot of people have outlawed comments and will not comment their code at all. I understand this but still comments have a really good use and I like to make a case for using them sparingly.

Do not use comments if not necessary

Sometimes better names make comments redundant and even improve the code because using the name always carries the meaning.

let price = 0; // price in cents
Enter fullscreen mode Exit fullscreen mode

vs

let priceInCents = 0;
Enter fullscreen mode Exit fullscreen mode

Often, comments are used to structure code. For structure we have better tools that never lie.

function processInput(input: string) {  
    // validate input  
    if (input.length < 10) {  
        throw "input too short"  
    }  
    if (input.length > 100) {  
        throw "input too long"  
    }  

    // remove colors  
    let result  = input.replace('red', '').replace('green', '').replace('blue', '');  

    // format result  
    result = result.trim().toUpperCase()  

    return result  
}
Enter fullscreen mode Exit fullscreen mode

If we just take the comments and make them into functions, the code is even more clear. You don't even have to look at the implementation details if you do not care at this point in time. It can also be used to contain ugly and unclear implementations (sometimes it is just not avoidable).

function processInput(input: string) {  
    validateInput(input);  

    let result = removeColors(input);  

    return formatResult(input)  
}

function validateInput(input: string) {  
    if (input.length < 10) {  
        throw "input too short"  
    }  
    if (input.length > 100) {  
        throw "input too long"  
    }
}

function removeColors(input: string) {  
    return input.replace('red', '').replace('green', '').replace('blue', '');  
}  

function formatResult(result: string) {  
    return result.trim().toUpperCase();  
}
Enter fullscreen mode Exit fullscreen mode

The above code very clearly shows the 3 responsibilities of the processInput function. validate, do and return formatted. I do not want to make the point that you always have to structure your functions this way. Often, having the validation inside the "mother" function is a good idea to show exactly what is going on. But when you feel the urge to write a comment to structure code, think about using a function for structure.

Use comments to explain the why, the odd and the consequences

What we, more often than not, can not illustrate with code structure is the why, the odd and the consequences of something. Everytime something would surprise you in a year or a new developer, this is a very good reason to introduce a comment.

the why

// we are moving between API's so we are calling new and old apis.
oldUsersApi.updateData(userData);
newUserApi.updateData(userData);
Enter fullscreen mode Exit fullscreen mode

the odd

// this is odd but the 3rd party client api enforces us to disconnect before we can connect
client.disconnect()
client.connect()
Enter fullscreen mode Exit fullscreen mode

the consequences

user.delete() // deleting the user will cascade deletion of all their data
Enter fullscreen mode Exit fullscreen mode

My guidelines for commenting code well

  • Only comment the why and only if not obvious
  • Always try to explain yourself in code first.
  • Use as explanation of intent.
  • Use as clarification of code.
  • Use as warning of consequences.

This article is extracted from a series of talks I gave.

Jaap Groeneveld - Software Engineering Principles

A talk about software engineering principles & clean code

favicon slideshare.net

Top comments (4)

Collapse
 
katafrakt profile image
Paweł Świątkowski

This is nice framework for when to use comments. I also think we went too far in eradicating the comments from codebases, while in many cases they are indeed useful.

Collapse
 
jgroeneveld profile image
Jaap Groeneveld

Yes I agree. Like all documentation they should be used purposefully but they are indeed useful!

Collapse
 
mcsee profile image
Maxi Contieri

great post!

Collapse
 
jgroeneveld profile image
Jaap Groeneveld

thank you :)