...by Daniel Szego
quote
"On a long enough timeline we will all become Satoshi Nakamoto.."
Daniel Szego

Wednesday, December 20, 2017

Solidity and Truffle Tips and Tricks - external vs public


Function modifiers can be explicitly set to external or to public. The default is always public. The difference between the two calls manifest if the function is called internally, if public functions are called externally it means always an extra call (via messages or transaction), however if they are called internally it does not manifest with an extra call. An external variable can always be called from another smart contract implying a transaction or a message in a transaction. If they need to be called internally an explicit external call has to be simulated with the this keyword:

contract Calls{

  function externalF() external {
  ...
  }

  function callInternally() public {
  this.externalF(); // internal function is called as external
  }
}

Using the this keyword and calling an external function internally is usually not a best practice and cost more gas. Instead, it is proposed to set a function to public if it can be called both from internal and from externally as well. There is one exception if the input value of a function contains an array, in such scenario forcing always the external call might be more gas efficient.