Code Smell 05 - Comment Abusers

Code Smell 05 - Comment Abusers

The code has lots of comments. Comments are coupled to implementation and hardly maintained.

Maxi Contieri
·Oct 24, 2020·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Problems
  • Solutions
  • Examples:
  • Sample Code
  • Detection
  • Relations
  • Refactorings
  • More info
  • Tags
  • Conclusion
  • Credits

TL;DR: Leave comments just for important design decisions. Don't explain the obvious.

Problems

  • Maintainability

  • Obsolete Documentation

  • Readability

  • Code and comments duplication.

Solutions

1) Refactor methods.

2) Rename methods to more declarative ones.

3) Break methods.

4) If a comment describes what a method does, name the method with this description.

5) Just comment on important design decisions.

Examples:

  • Libraries

  • Class Comments

  • Method Comments

Sample Code

Wrong

<?

final class ChatBotConnectionHelper {
    // ChatBotConnectionHelper is used to create connection strings to Bot Platform
    // Use this class with getString() function to get connection string to platform

    public $id; // ChatBot Id

    function getId() { // Gets id value
    }

    function setId($id) { // Sets id value
    }

    function getString() {
        // Get Connection String from Chatbot
        // ....
    }
}

Right

<?

final class ChatBotConnectionSequenceGenerator {

    private $name;

    function connectionSequence() {
        // ....
    }
}

Detection

Linters can detect comments and check the ratio of comments/lines of code against a predefined threshold.

Relations

Refactorings

More info

Refactoring Guru

What is in a name

Comments as a bad sign

How to comment your code

Tags

  • Comments

  • Declarative

Conclusion

Leave comments just for important design decisions. Don't comment on a method with a bad name, rename it.

Credits

Photo by Volodymyr Hryshchenko on Unsplash


If you have to spend effort looking at a fragment of code and figuring out what it’s doing, then you should extract it into a function and name the function after the what.

Martin Fowler


This article is part of the CodeSmell Series.

 
Share this

Impressum

Technical Opinions are my own. I don't have the revealed truth.

Software Design is a creative activity. These are hints and not rigid rules.

I write on BackEnd Business Systems and OOP Design. My advice/experience might not suit other systems.

You can write me at info(at)maximilianocontieri.com