DEV Community

Discussion on: Clean up your code by applying these 7 rules ⚡️

Collapse
 
emilesteen profile image
Emile Steenkamp • Edited

You don't need comments to explain what your code is doing. Better practice is to use code to explain what the code is doing.

for your last example you could rather do this:

Graph graph = getGraph("money-made");
displayGraph(graph);

function getGraph(String source) {
    Tuple[] graphPoints = server.getGraphPoints(source);
    Graph graph = new Graph(
        new Tuple<int>(0, 0),
        new Tuple<int>(1000, 1000),
        graphPoints
    );
    return graph
}

function displayGraph(Graph graph) {
    JFrame window = new JFrame("Data Graph");
    window.add( graph.getJPanelRepresentation() );
}
Enter fullscreen mode Exit fullscreen mode

In this example out functions are telling the developer exactly what is happening and splitting the code up into sections instead of comments. A common issue is that comments can lie. If you update the code and forget to update your comments your comments will be lying and can confuse you. If your code is readable you shouldn't need comments to explain what is happening.

Uncle Bob explains the use of comments much better in this talk:
youtu.be/2a_ytyt9sf8
and I would recommend watching the entire clean code series if you have time.

Collapse
 
baenencalin profile image
Calin Baenen

Is it bad, or to a disadvantage to use comments, then?

Thread Thread
 
darlantc profile image
Darlan Tódero ten Caten

Yes, experience teaches us that comments must be the last resource to be used only when the logic is very hard to explain. Even so in most times is better to break that complicated logic into multiple small functions to be easy to read that code later.

Always try to name all variables, functions, and classes with meaningful names that self explain itself, avoiding the usage of comments.

Also, another problem with comments is that when the code changes very often the developers don't update the comments (the linter don't tell us that they are wrong now) and they don't reflect anymore the current logic of the code.