Why You Need View Functions and Pure Functions in Solidity

Solidity supports two types of functions; View Functions and Pure Functions.

Understanding State Mutability is key to optimize your smart contracts and let users to save gas fees.

State Mutability View Functions Pure Functions others
modify the state 🚫 🚫 ✅
read from the state 🚫 ✅ ✅

How View Functions Look Like

Function declaratives come with view mark. View functions do read from state variables, like block.timestamp, but never modify state variables.

No modification means no transaction. No transaction means no gas fees. Using view functions as much as possible to make your smart contracts effecient.

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.9.0;

contract C {
    function f(uint a, uint b) public view returns (uint) {
        return a * (b + 42) + block.timestamp;
    }
}

Not only writing to state variables, emitting events or sending Ether via calls are also considered modifying the state (you can check the full list in the documentation).

How Pure Functions Look Like

Function declaratives come with pure mark. Pure functions never read nor modify state variables.

Using pure functions enforces programmers to introduce Functional Programming paradigm partially into your smart contracts. Pure functions are considered small and precise, meaning it may introduce fewer software bugs.

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.9.0;

contract C {
    function f(uint a, uint b) public pure returns (uint) {
        return a * (b + 42);
    }
}

Accessing address(this).balance or <address>.balance is also considered reading from the state. Accessing block, tx, msg is also reading from the state (you can check the full list in the documentation).

2022-10-26