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

Laravel Http Client Overview and Monitoring

Laravel HTTP client was introduced starting from version 10 of the framework, and then also made available in all previous versions. It stands out as a powerful tool for making HTTP requests and handling responses from external services. This article will delve into the technical foundations of the Laravel HTTP client, its motivations, and how

Laravel Form Request and Data Validation Tutorial

In this article I will talk about Laravel Form Request to send data from your application frontend to the backend. In web applications, data is usually sent via HTML forms: the data entered by the user into the browser is sent to the server and stored in the database eventually. Laravel makes it extremely simple

Upload File in Laravel

You can upload file in Laravel using its beautiful unified API to interact with many different types of storage systems, from local disk to remote object storage like S3. As many other Laravel components you can interact with the application filesystem through the Storage Facade: Illuminate/Support/Facades/Storage This class allows you to access storage drivers called