Lesson 05 of 25
Functions & Visibility
public, private, internal, external — control who can call your functions.
BeginnerFunction Syntax
A Solidity function declares its visibility, state mutability, parameters, and return types.
Solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract FunctionDemo {
uint256 private value;
// Function anatomy:
// function <name>(<params>) <visibility> <mutability> returns (<types>)
function setValue(uint256 _val) public {
value = _val; // modifies state
}
function getValue() public view returns (uint256) {
return value; // reads state, doesn't modify
}
function double(uint256 x) public pure returns (uint256) {
return x * 2; // neither reads nor modifies state
}
}
Visibility Modifiers
public— callable from anywhere: externally, internally, by derived contractsprivate— only callable within THIS contract (not even derived contracts)internal— callable within this contract AND derived contractsexternal— only callable from outside the contract (more gas efficient for large data)
Solidity
contract Visibility {
uint256 private secret = 42; // only this contract
uint256 internal shared = 10; // this + children
uint256 public open = 99; // everyone
function _helper() private view returns (uint256) {
return secret;
}
function getAll() external view returns (uint256, uint256) {
return (_helper(), shared); // can call private internally
}
}
State Mutability
view— reads state, does NOT modify it. Gas-free when called externally.pure— neither reads NOR modifies state. Useful for math utilities.- (no keyword) — can read and write state. Costs gas.
payable— can receive Ether. Covered in Lesson 15.
Solidity
contract Mutability {
uint256 public count;
function increment() public { // modifies state
count++;
}
function getCount() public view returns (uint256) { // reads state
return count;
}
function add(uint256 a, uint256 b) public pure returns (uint256) { // pure math
return a + b;
}
}
Multiple Return Values
Solidity supports returning multiple values from a single function using tuples.
Solidity
contract MultiReturn {
function minMax(uint256[] memory arr)
public pure returns (uint256 min, uint256 max)
{
min = arr[0];
max = arr[0];
for (uint i = 1; i < arr.length; i++) {
if (arr[i] < min) min = arr[i];
if (arr[i] > max) max = arr[i];
}
// named returns automatically returned
}
function useMinMax() public pure returns (uint256, uint256) {
uint256[] memory nums = new uint256[](3);
nums[0] = 5; nums[1] = 2; nums[2] = 8;
(uint256 lo, uint256 hi) = minMax(nums);
return (lo, hi); // returns (2, 8)
}
}