Replace comments with better code

Valerio Barbera

Hi, I’m Valerio, software engineer, founder and CTO at Inspector.

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 to help developers in two ways:

  • Navigate the code better – use comments to lead the IDE behaviour;
  • Add more contextual information to avoid misunderstanding about why a 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

class Math
{
   public function calc() 
   {
     // Add b to a 
     $c = $this->a + $this->b;     // return the result of a + b 
     return $c;
   }
}

The code above could be the result of a meeting where the team is recommended to add comments on the code.

Write expressive code

Repeating the code is the worst you can do. Add comments that describe what your code is doing when it would be much clearer to read the code itself means that you are wasting time. And other developers will spend time too to investigate useless documentation.

Junior developers rely on comments to tell stories when they should rely on code to write their stories. It’s a typical appproach for less experienced developers.

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. Make it explains its purpose alone.

Take a look at the example below:

<?php

/**
 * Calculate spending limit by customer income and try to find a room above that 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->findRoomByPrice(
            $this->calculateCustomerSpending($income)
        );
    } catch (\Eception $exception) {
        // do something with error
    }
}public function findRoomByPrice($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 exists using the code itself.

My advice is to not underestimate this aspect. If too many comments are present in the code it increases exponentially the risk that you, and the other developers, will pay less attention to their presence. The risk is to propagate wrong information in the documentation.

Very often comments are obviously needed to explain more complex scenarios. In modern IDE 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 drastically improving maintainability.

New to Inspector?

Get a monitoring environment specifically designed for software developers to avoid server or infrastructure configuration.

Developers may be uncomfortable installing and configuring software at the server level. Server level configurations are out of the software development lifecycle or are even handled by external teams.

Thanks to Inspector, you will never need to install things at the server level or make complex configurations in your cloud infrastructure.

Inspector works with a lightweight software library that you can install in your application like any other dependencies based on the technology or framework. Check out our GitHub organization for more information: https://github.com/inspector-apm

Visit our website for more details: https://inspector.dev

Related Posts

How to configure HTTPS in Laravel Homestead

How to enable HTTPS in Laravel Homestead

Hi, I’m Valerio Barbera, software engineer, founder and CTO at Inspector. In this article I’ll show you how to enable HTTPS for your local applications served by Homestead. I met this need because I am working to implement browser notifications for Inspector using Pusher/Beams. But Beams requires that the application be necessarily served over HTTPS.

Laravel cron scheduling and its secrets

Hi, I’m Valerio Barbera, software engineer, founder and CTO at Inspector. Laravel tasks scheduling is one of the most useful features of the framework.The official documentation clearly explains what it is for: In the past, you may have written a cron configuration entry for each task you needed to schedule on your server. However, this

Laravel validation and custom rules in Inspector

Hi, I’m Valerio Barbera, software engineer, founder and CTO at Inspector. Data validation is one of the fundamental features in any application and it is something developers manipulate almost every day. The value a software provides to users is often a function of the quality of data it is able to manage. Laravel ships with

How to build scalable applications

Read the best news, tips and other direct in your inbox