Solidity – Why and When to Use Private for Mapping in Smart Contracts

visibility

mapping(address => uint) private _balances;

function balance() public view returns (uint) {
    return _balances[msg.sender];
}

My question is. Should you/Why/When should you use private _balances, versus just using public and not having to write a getter for the function

mapping(address => uint) public balances;

What's the main difference?

Best Answer

The only reason to write your own getter and use private for the mapping is if you want to combine the mapping somehow with some other state of the contract (add some additional value to the getter).

In writing your own getter function, you are doing the same action that solidity is going to do when it compiles state variables and functions into byte code.

Related Topic