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

[Resolved] Integrity constraint violation – Fast tips

If you are dealing with the error: “Integrity constraint violation: Cannot add or update a child row: a foreign key constraint fails“, you are in the right article. Usually you encounter this error when you add a new column to a table and declare it as a Foreign Key.  In a SQL database, a foreign

How to monitor Guzzle Http Client – PHP Fast tips

Guzzle is a popular PHP HTTP client that makes it easy to send HTTP requests and create web service libraries. The most popular PHP frameworks provides an internal Http Client service, and they are simply a customized implementation of the Guzzle Http Client: Guzzle is widely used for two main reasons: Customization and Flexibility For

Post your Feature Requests and contribute to our product journey

I’ve recently been thinking about the best way to allow Inspector’s users to share the features they’d like to find in Inspector. Often I ask for feedback or investigate new feature requests during live chat sessions. In the first instance developers drop in a live chat asking for support. Very often these chats lead to