Replace comments with better PHP 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. So, 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. 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 can do is consider the possibility of restructuring the code you wrote, and 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.

Comments are obviously needed to explain complex code blocks, but they are useful to improve code navigation in modern IDE too.

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.

Application monitoring

If you found this post interesting and want to drastically change your developers’ life for the better, you can give Inspector a try.

Inspector is an easy to use Code Execution Monitoring tool that helps developers to identify bugs and bottlenecks in their application automatically. Before customers do.

screenshot inspector code monitoring timeline

It is completely code-driven. You won’t have to install anything at the server level or make complex configurations in your cloud infrastructure.

It works with a lightweight software library that you can install in your application like any other dependency. Check out the supported technologies in the GitHub organization.

Create an account, or visit the website for more information: https://inspector.dev

Related Posts

How to make Vite Hot Module Replacement work on Windows

As many of our community members already know, we recently started the renovation of the Inspector dashboard UI with a fresh new design and a modern technology stack. In this article I will explain why we decided to leave Webpack and embrace Vite as assets build tool and Hot Module Replacement. I will show you

Http traffic monitoring for Slim framework

This article follows the release of the first version of the monitoring library for Slim framework. Thanks to this package you can fully monitor the HTTP traffic against your application based on Slim. It takes less than one minute to get started. First let me give you a bit of context. Introducing the Slim framework

How to use wildcards in ExpressJs and Fastify monitoring libraries

With the booming software economy, the demand for new applications and software-defined automations is set to grow in the future years. Companies in any industry are creating software in the form of internal business tools, productivity tools, integrations, automations, and more. As a result, there is a need for tools that make it easy to

How to build scalable applications

Get the e-book about the Inspector scalability journey.