DEV Community

Cover image for Code Smell 146 - Getter Comments
Maxi Contieri
Maxi Contieri

Posted on • Edited on • Originally published at maximilianocontieri.com

Code Smell 146 - Getter Comments

Comments are a code Smell. Getters are another code smell. Guess what?

TL;DR: Don't use getters. Don't comment getters

Problems

  • Comment Abusers

  • Readability

  • Getters

Solutions

  1. Remove getter comments

  2. Remove getters

Context

A few decades ago, we used to comment on every method. Even trivial ones

Comment should describe only a critical design decision.

Sample Code

Wrong

pragma solidity >=0.5.0 <0.9.0;

contract Property{
    int private price;   

    function getPrice() public view returns(int){           
           /* returns the Price  */
        return price;
    }
}
Enter fullscreen mode Exit fullscreen mode

Right

pragma solidity >=0.5.0 <0.9.0;

contract Property{
    int public _price;   

    function price() public view returns(int){        
        return _price;
    }
}
Enter fullscreen mode Exit fullscreen mode

Detection

[X] Semi-Automatic

We can detect if a method is a getter and has a comment.

Exceptions

The function needs a comment, that is accidentally a getter and the comment is related to a design decision

Tags

  • Comments

Conclusion

Don't comment getters.

They add no real value and bloat your code.

Relations

Credits

Photo by Reimond de Zuñiga on Unsplash


Code should be remarkably expressive to avoid most of the comments. There'll be a few exceptions, but we should see comments as a 'failure of expression' until proven wrong.

Robert Martin


This article is part of the CodeSmell Series.

Top comments (5)

Collapse
 
joolsmcfly profile image
Julien Dephix

Any reason why you changed price to _price in your "Right" code version?

Some people like to prefix private variables with an underscore but yours is public. 🤔

Collapse
 
mcsee profile image
Maxi Contieri

My code is generated by Copilot.
It changed it.
I am fine with both conventions

Collapse
 
joolsmcfly profile image
Julien Dephix

I see. I would have marked it as private in the “wrong” version to begin with. Otherwise having a getter on a public property is unnecessary.

Thread Thread
 
mcsee profile image
Maxi Contieri

you are right, I'll change it to private

Thread Thread
 
joolsmcfly profile image
Julien Dephix

Change it in the "Right" version and it's all good!