Solidity – Accessing Getter Functions for Public Variables

soliditystate-variable

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?

Best Answer

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.