1

In the Openzeppelin ERC721.sol contract, there are private variables introduced:

// Token name
string private _name;

// Token symbol
string private _symbol;

These variables are then assigned a public view functions to display their content:

 /**
 * @dev See {IERC721Metadata-name}.
 */
function name() public view virtual override returns (string memory) {
    return _name;
}

/**
 * @dev See {IERC721Metadata-symbol}.
 */
function symbol() public view virtual override returns (string memory) {
    return _symbol;
}

Why are these private instead of public? Nobody can change the values in either of the cases, as mentioned here.

1
  • Those functions are virtual which mean that you can override them if you need it
    – Majd TL
    Commented Aug 5, 2022 at 18:21

1 Answer 1

2

The pattern you noticed is competing with the approach of using an internal storage variable.

The general idea here is you can read the variables and not write. It allows the contract to make some extra guarantees, for example the variable could be read only. I have an issue open to request a language feature for public/private variables.

Overall this is a common pattern in object-oriented design so it is natural and will keep getting used.

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.