We have already covered Variables and Data Types of Solidity in the last tutorial. Today, we will cover the structure of functions, the visibility specifiers and state mutability of functions and variables in Solidity.
Structure of a Function in Solidity
Functions, in any programming language are a way to reuse code. They ensure you don’t have to write the same code in the program again and again. You write the code once, and then use that code as many times in your program as you want. This can be done by invoking (calling) the function.
Solidity is no different than any other programming language. It uses functions to enable code re-usability and modularity. Here is how a typical Solidity function looks like:
The above code is the syntax of a simple Solidity function.
Visibility of Functions and Variables
- Public: Public is the default visibility specifier of functions in Solidity. Public functions can be called internally (from within the smart contract) and externally (from outside the smart contract). Everyone has access to public functions. Getter-Setter functions are automatically generated without the need of us writing them explicitly for variables declared as public.
- External: External functions can be called from other smart contracts and via transactions. An external function cannot be called internally (i.e. from within the smart contract). External functions use less gas when they receive large arrays of data, and are sometimes more efficient. There is no external visibility for variables.
- Internal: This is the default visibility specifier for variables in Solidity. Internal variables and functions can be accessed only from within the smart contract or from the smart contract deriving from it.
- Private: The private visibility specifier is used for variables and functions which are to be accessed strictly from within the contract. These functions and variables cannot be accessed from contracts deriving from them.
State Mutability of Functions
- Pure Functions: Pure Functions are functions that promise to not read from or modify the state of storage data. All the data the function is concerned with is defined in its scope.
- View functions: Unlike Pure functions, View functions read data from the storage. But they cannot modify the state of that data.
- Payable functions: Functions that have to accept/receive funds (in ether) when they are called are declared as payable. If you try to send ether to a function not declared as payable, the transaction is rejected.