0

OpenZeppelin's ERC20 token contract contains the following declaration of decimals, and then a getter function for accessing that variable:

uint8 private decimals;
function decimals() public view returns (uint8)

It seems they could have simply used public in the definition and accomplished the same result with less code.

uint8 public decimals;

Does anyone know why the private variable with public getter is preferred?

1 Answer 1

0

OZ often writes variables this way. The reasoning behind it is to keep the variables isolated in the ERC20 contract and only allow as much access as necessary.

For example, balances will be stored as private _balances. This is to ensure that all accounting makes sense. If it were declared as public balances and 'freely accessible' in contract A which inherits ERC20, then an inexperienced user might accidentally modify balances. This should only happen in the pre-defined functions _mint, _burn or _transfer (which have internal access), so that any necessary accounting can be ensured to happen (_totalSupply should always be updated with any token balance change and the correct events should be emitted).

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.