0

Are there any benefits from fetching stored data into other functions by calling a function to call a private variable, instead of calling the private variable directly? What is best practices?

example

 contract PlayerExample {

    uint private maximumPlayers

    uint private players;

    function playersCount() public view returns (uint) {
        return players;
    }

    function playerSlotsLeft() public view returns (uint) {
        return (maximumPlayers - players);
        //or is it better to do 
        //return (maximumPlayers - playersCount());
    }
 }
0

From a gas perspective - specifically, if this were ever being called by another contract as part of a transaction, rather than just a call being made directly - then not having another function call on the stack is going to be cheaper:

pragma solidity ^0.5.1; 

contract PlayerExample {
    uint private maximumPlayers = 10;
    uint private players = 5;

    function playerSlotsLeft() public view returns (uint) {
        return (maximumPlayers - players);
    }
}
  • Transaction cost: 21874
  • Execution cost: 602

pragma solidity ^0.5.1; 

contract PlayerExample {
    uint private maximumPlayers = 10;
    uint private players = 5;

    function playersCount() public view returns (uint) {
        return players;
    }

    function playerSlotsLeft() public view returns (uint) {
        return (maximumPlayers - playersCount());
    }
}
  • Transaction cost: 21931
  • Execution cost: 659
  • Do you think it's a valuable trade off to have another function call on the stack if it aids in readability of the source code? – NowsyMe Jul 28 at 12:31
  • 1
    In this case - and in cases where the function is simply acting as an internal getter for a variable - no. In my opinion all you're doing is adding a level of indirection, making it less readable. Instead of just looking for the variable definition - which in an ideal world would be a) well-commented, b) have an intuitive name - you first have to look for the function, realise that it's just returning the variable, and then look for the variable. And it (potentially) costs more gas :-) – Richard Horrocks Jul 31 at 8:10
  • (Even if you're sure this code would never be called by another contract as part of a transaction, and only ever be called as part of a "call", you have to remember that a larger contract costs more to deploy in the first place. Maybe one such function wouldn't make much different, but if you end up writing a function for each variable then costs are going to increase accordingly.) – Richard Horrocks Jul 31 at 8:12
0

If you use a function you have the possibility to add extra functionality to it when needed, for example access checks. Otherwise I don't see much benefits in using a function.

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.