Function Modifiers - view and pure
View functions :
Functions marked as "view" are read-only functions that do not modify the state of the contract.
They can only read data from the blockchain and return values.
These functions are free to call and do not consume any gas when invoked by external actors.
View functions are primarily used for querying and fetching data from the blockchain.
Example :
Imagine a voting contract where users can check the number of votes cast for a particular candidate. In this case, you can use a "view" function to retrieve this information without altering the contract's state.
Solidity
Copy
pragma solidity ^0.8.0;
contract Voting {
mapping(string => uint256) public votes;
function getVotesForCandidate(string memory candidateName) public view returns (uint256) {
return votes[candidateName];
}
}
In this contract, the getVotesForCandidate function is marked as "view" because it only reads data from the votes mapping. Users can query the number of votes for a candidate without changing the contract's state.
Pure functions :
They do not read or modify the state of the contract and do not access any external data.
Pure functions are entirely deterministic and rely only on their input parameters.
They also do not consume any gas when called externally.
Example :
Suppose you have a contract that performs mathematical calculations, such as addition, subtraction, multiplication, or division. These operations are deterministic and don't involve contract state changes. For such things we can use "pure" functions for these calculations.
Solidity
Copy
pragma solidity ^0.8.0;
contract MathOperations {
function add(uint256 a, uint256 b) public pure returns (uint256) {
return a + b;
}
function multiply(uint256 a, uint256 b) public pure returns (uint256) {
return a * b;
}
}
In this contract, both the add and multiply functions are marked as "pure" because they perform mathematical calculations based on their input parameters and do not alter with the contract's state or external data. Users can call these functions to perform calculations without altering the contract's state.