Back to homepage

Solidity funcions visibility: public, private, internal and external

Published

Make sure to check out my previous article about Solidity functions: Solidity fundamentals: all about functions

Private and Public Functions

In Solidity, functions are public by default. This means anyone (or any other contract) can call your contract's function and execute its code.

This isn't always desirable as in some cases we would prefer to make our functions only availalbe to other functions within our contract. In that case we can specifically mark our functions as private. Find below an example:

pragma solidity ^0.8.4;

contract MyContract {
  uint[] savedNumbers;

  // this function is public by default so no need to specify it
  function getNumber(uint _index_) returns (uint) {
    return savedNumbers[_index];
  }
  // this function can only be called
  function _addNumber(uint _number) private {
    savedNumbers.push(_number);
  }


}

As you can see, we use the private keyword after the function name to indicate it.

Note: as with function parameters, it's common practise to start private function names with an underscore (_).

Internal and External Functions

In addition to public and private, Solidity has two more types of visibility for functions: internal and external. These visibility modifiers are related with inheritance between contracts.

  • internal is the same as private, except that it's also accessible to contracts that inherit from this contract.
  • external is similar to public, except that these functions can ONLY be called outside the contract but NOT by other functions inside that contract. It's a weird scenario but Solidity gives us the option 😉

The syntax is the same as private and public. Find an example below:

contract Pokemon {
  uint private capturedPokemons = 0;

  function capture() internal {
    capturedPokemons++;
  }
}

contract Pikachu is Pokemon {
  uint private pikachuEncounters = 0;

  function PikachuEncounter() public returns (uint ) {
    pikachuEncounters++;
    // We can call this function from a different contract because it's internal
    // and it inherits
    capture();

    return pikachuEncounters;
  }
}

TAGS

If you enjoyed this article consider sharing it on social media or buying me a coffee ✌️

Buy Me A Coffee