1

Many token contracts have unrestricted getter functions for state variables, which seems redundant (eg, see OpenZepplin's ERC20 contract). For example, a contract could have it this way:

uint private _totalSupply;

function totalSupply() view public returns (uint) {
return _totalSupply
}

or this way:

uint public totalSupply;

Web3.js and solidity would use the exact same syntax--totalSupply--to retrieve the variable "totalSupply." As the former is more common, but also more verbose, I presume I am missing some way in which a getter function dominates querying a contract directly. Can someone enlighten me?

  • You're missing the fact that in the first case, only this contract can change the value of the totalSupply variable, whereas in the second case, every inheriting contract can also change the value of the totalSupply variable. That is why OZ have moved from public variables on their v1 to private variables on their v2. Off-chain-wise (e.g., web3.js), both paradigms are identical of course. – goodvibration Sep 11 at 21:37
  • I don't see it. The mutability of totalsupply is not affected by whether it is private or public. – Eric Falkenstein Sep 11 at 22:40
  • An inheriting contract can change it if it's public, but not if it's private, what exactly don't you see here??? – goodvibration Sep 12 at 8:56
  • I was thinking purely about a single contract, not inheritance. So, I see it now from that perspective. – Eric Falkenstein Sep 12 at 17:01
1

You're missing the fact that in the first case, only this contract can change the value of the totalSupply private variable, whereas in the second case, every inheriting contract can also change the value of the totalSupply public variable.

BTW, that is why OpenZepplin moved from public variables to private variables when they released v2.

Off-chain-wise (e.g., web3.js), both paradigms are identical of course, because the Solidity compiler auto-generates a public function for every public state-variable in the contract.

| improve this answer | |
1

It's a matter of better reusability. You can't override generated getter functions in possible child contracts but you can if the function is explicitly written out (like in your first example). Also I would claim it's a matter of better readability: many outside people don't know about generated getter functions so it's difficult for them to understand the code with implicit getter functions.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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