2

I'm curious why interfaces don't accept public variables as implementations, since public variables have getter functions generated for them.

For example why couldn't the ERC20 balanceOf interface function be implemented by a public balanceOf variable.

interface

function balanceOf(address tokenOwner) public constant returns (uint256 balance);

implementing contract

mapping (address => uint256) public balances;
  • I assume you meant for the state variable to also be named balanceOf. There's nothing wrong with implementing the interface that way, but it seems that the Solidity compiler doesn't recognize that you have properly implemented the interface when you do it that way. – user19510 Apr 6 '18 at 18:41
1

Mostly, it's for two main reasons:

1) Functions aren't variables and they are not interchangeable

2) Functions support a lot more things than variables do. Actually variables don't support any functionality, just their (convenience) getters.

Functions and variables behave quite differently. You have to implement the interface's functions, which literally means that they have to have an implementation - they have to do something. A getter doesn't really do anything else than return the value of a variable.

For example your interface function balanceOf: nobody says exactly how you should implement the function - it just needs to have the given signature and the rest is up to you. Nobody tells you it has to return any meaningful value - maybe you decide to always return 0 and it's totally fine from the interface's point of view. Or maybe you want to do complicated calculations - you can't do any of that with just a getter function.

I found someone else also having the same idea: https://github.com/ethereum/solidity/issues/3514

  • Hmm fair enough, but if all the interface function cares about is the the method signature, what is it about the generated getter that is not satisfying this? A getter just returns the value, but from a method signature point of view, this is exactly what it is asking for. Thanks for the link! – arete Apr 6 '18 at 17:15
  • The getter does not have the same signature. The getter returns you a mapping, the function returns uint. And so on. – Lauri Peltonen Apr 6 '18 at 17:18
  • I believe the getter returns uint256 in this case and takes an address as a parameter. solidity.readthedocs.io/en/develop/… – arete Apr 6 '18 at 17:49
  • Oh, I just learned something new :) Thanks and sorry about that. – Lauri Peltonen Apr 6 '18 at 18:11

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.