Replace Comments With Better Code

Written by valerio-barbera | Published 2020/03/14
Tech Story Tags: php | laravel | programming | backend | php7 | web-development | optimization | code-quality

TLDRvia the TL;DR App

Hi, I’m Valerio, software engineer from Italy.
I spent these last 10 years working as software engineer with any kind of companies and colleague.
Software development is collaborative by nature. If you’re working for a company, regardless of size, you’re obviously working with others. 
I strongly believe in the comments as documentation for certain functions or entire classes because they can help developers in two way:
  • Navigate the code using comments to lead the IDE behaviour;
  • Add more contextual information to avoid misunderstanding about why that code block was designed that way (increase perofmance, resolve bug, etc…)
When you are part of a team, comments in the code can cause discussions and disagreements. Let us agree on the concept of  "comments in the code".
<?php

public function calc() 
 {
  // Add b to a 
  $c =  $this->a +  $this->b;

  // return the result of a + b 
  return  $c;
}
This above could be the result of a meeting where the team is recommended to add comments on the code.
Repeating the code is the worst you can do, adding comments that describe what your code is doing when it would be much clearer to read the code itself means that you waste time and other developers will spend time too to investigate unless documentation.
Junior developers rely on comments to tell stories when they should rely on code to write their stories. Less experienced developers tend to use comments to describe the story behind a code block.
We can even be more expressive taking care on the names of classes, functions and variables without writing a line of comments.
If you feel the need to write comments to explain what your function is for, the first thing you need to do is consider the possibility of restructuring the code you wrote to make it explain its purpose itself. Take a look on the example below:
<?php

/**
 * Calculate spending limit by customer income and try to find a room to a lower price.
 */
public function rentRoom($income)
{
    $spending = round(($income*0.15) / 12);
    foreach ($this->rooms as $room) {
        if ($room->price <= $spending) {
            return $room;
        }
    }
    throw new RoomNotFoundException();
}
Only one comment line could be acceptable. Or could we review the code to make it clearer, modular and avoid any comment?
<?php

/**
 * Rent a room based on customer's income
 * 
 * @params integer $income
 */
public function rentRoom($income)
{
    try {
        $this->findRoomByPriceLimit(
            $this->calculateCustomerSpending($income)
        );
    } catch (\Eception $exception) {
        // do something with error
    }
}


public function findRoomByPriceLimit($limit) 
{
    foreach ($this->rooms as $room) {
        if ($room->price <= $limit) {
            return $room;
        }
    }
    throw new RoomNotFoundException();
}


public function calculateCustomerSpending($income, $percentage = 15)
{
    return round(
        ($income*($percentage/100)) / 12
    );
}
The code is more verbose and there is no need for comments.
The numbers now have a label and the functions have a name that clearly explains what they do. This example may seem a little excessive if taken individually. What you need to focus your attention on is the strategy, the value of explaining how and why that code is found there using the code itself.
My advice is to not underestimate this aspect. If too many comments there are in the code the risk that you, and the other developers, will pay less attention to their presence increases exponentially also propagating in the documentation old and wrong information.

Conclusion

Very often comments are obviously needed to explain more complex scenarios or link to bugs and it is not possible to do so using only the names in the code.
In modern IDE (like PHPStorm or VSCode) comments are often useful to improve code navigation.
In any case, the next time you feel the need to write comments you can ask yourself if it is possible to have the same readability using the code itself improving maintainability of your code base.

New to Inspector?

Are you looking for a “code-driven” monitoring tool instead of having to install things at the server level?
Get a monitoring environment specifically designed for software developers avoiding any server or infrastructure configuration.
Thanks to Inspector, you will never have the need to install things at the server level or make complex configuration in your cloud infrastructure to monitor your application in real-time.
Inspector works with a lightweight software library that you can install in your application like any other dependencies based on the technology you are using to develop your backend.
Developers are not always comfortable installing and configuring software at the server level, because these installations are often managed by external teams, and they are out of the software development lifecycle.
Visit our website for more details: https://inspector.dev/
Previously published at https://www.inspector.dev/replace-comments-with-better-code/

Written by valerio-barbera | Simple Code Execution Monitoring, built for developers
Published by HackerNoon on 2020/03/14