2

So I discovered that solidity is generating automatic getter for public property. I was wondering why is not used more often, especially in ERC20 Contract. For example the default ERC 20 contract is using a specified getter for the decimals.

    string private _name;
    string private _symbol;


    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

Why are they not using?

string public name
string public symbol

Am I missing something? Is it for security reasons? What are the advantages?

Many thanks in advance

1 Answer 1

3

As you can see by the keyword virtual these getters can be overridden in the derived contracts. Someone who might want to change the way those getters behave could use this property to do just that.

Another thing for me is just simplifying naming. By convention underscore before the name of the variable notes that it is a global variable (state variable in Solidity), and the ones with the underscore after the name are local (memory variables). Getter does not really need that distinction and simplification may take place.

2
  • 1
    Many thanks for the clear reply. It make sense. On the naming I agree but I was wondering if using default getter are reducing the contract size as well? I discovered this while I was trying to optimze my code in order to avoid reaching the 24kb limit
    – Anselme
    Dec 31, 2021 at 21:40
  • 2
    Public name and symbol would have the same default functions, and they would still be included into the compiling code so the size would not actually change. As long as you have either of the combinations of "private variable and custom public getter" or "public variable and default getter", but not both (since that would result in have twice as much code as is necessary), the size should be the same. Dec 31, 2021 at 22:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.