Please don't add redundant doccomments

May 5th 2022 | ~ 3 minute read

Preface

Ah, doccoments, love them or hate them, they have become prevalent in certain programming languages. They're great in languages without native type hinting support, like JavaScript, but they quickly become redundant if used excessively. I'd argue that they hurt readability of your code by increasing noise with irrelevant and redundant information.

Reasoning

I'm a PHP developer, so my main gripes are with PHP. More often than not, when reading PHP code, you'll see a lot of doccomments. The reasoning behind them used to make sense in the olden days, where PHP's type hinting system was either non existent or in its infancy. And while PHP itself has moved on, the developers, apparently, have not.

The gripe

The story goes on something like this. I'd open a PHP file someone else wrote and I'd be greeting with something resembling this:

<?php

declare(strict_types=1);

namespace App\Services;

class FooService
{
    /**
     * Store data.
     *
     * @param array $data
     */
    private array $data = [];

    /**
     *
     * Data setter.
     *
     * @param array $data
     * 
     * @return FooService
     */
    public function setData(array $data): FooService
    {
        $this->data = $data;

        return $this;
    }

    /**
     *
     * Transform data.
     *
     * @return array
     */
    public function transform(): array 
    {
        return array_map(
            fn(int $item): int => $item * 2,
            $this->data,
        );    
    }
}

Now you, my dear reader, tell me what do these comments add that isn't immediately inferred from the actual code? Nothing, that's right! The type declarations of parameters and return values don't add anything of value, they just repeat what the code has already stated on its own. I could delete them and actually improve readability.

Now, I'm not saying doccoments don't have their use case, they do, but this is not one of them. The purpose of doccoments, as the name implies, is to document your code. Adding redundant information doesn't qualify as documentation. Instead, make a concerted effort at explaining what the parameters, properties and methods are for. Don't go blindly adding doccomments, because you saw someone else do it, or worse, if your IDE told you to add them.

Conclusion

Think about what you write. Writing good comments is as valuable of a skill as coding itself. You've got all the space in the world for clear, actually helpful comments. So use it! Please...