View and Pure
View
The view keyword is a modifier used in Solidity to indicate that a function does not modify the state of the contract. View functions are able to access values from storage, but cannot modify them.
It allows the function to call other functions which do not modify the state, while still disallowing other functions which do modify the state.
The view keyword can also be used to make contracts more secure, as it ensures that data cannot be modified accidentally.
Since no state changes are made, the means that view functions can be called without incurring any gas costs.
Conditions for a statement to be considered as “modifying the state”:
State variables being written to.
Events being emitted.
Other contracts being created.
selfdestruct
being used.ETH being sent via calls.
Calling functions that are not marked view or pure.
Low-level calls being used.
Inline assembly containing certain opcodes being used
Pure
Pure function is one that does not interact with the blockchain in any way, including reading state of variables. It is self-encapsulated.
A pure function does not:
Read or write to the blockchain
Create or send a transaction
Access any state variables
Call any other functions
A pure function can ONLY call another pure function.
Last updated