In Solidity, the view
modifier is used to indicate that a function does not modify the state of the contract. It is a declaration to both the compiler and external callers that the function does not alter any persistent data within the contract. As a result, functions marked as view
are free to be called without creating a transaction, and they do not consume gas when called from outside the contract.
Here is an example of a function with the view
modifier:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract ViewExample {
uint256 public data;
// Function without modifying state (view)
function getData() public view returns (uint256) {
return data;
}
// Function modifying state (not view)
function setData(uint256 newValue) public {
data = newValue;
}
}
In this example:
getData
is marked as view
, indicating that it only reads from the state but does not modify it.setData
modifies the state, and therefore, it does not have the view
modifier.
The view
modifier (and its synonym constant
) is a helpful tool for ensuring that certain functions do not accidentally modify state. If you attempt to modify state within a function marked as view
, the compiler will raise an error.
It’s important to note that functions marked as view
can be called for free, without creating a transaction. However, if they are called within a transaction (e.g., from another contract function that modifies state), the entire transaction will be treated as a regular transaction, and gas will be consumed accordingly.
Using view
is a good practice when you want to allow external parties to query information from your contract without incurring gas costs. Additionally, it provides clarity to developers and tools about the intention of the function.