0
0
Blockchain / Solidityprogramming~15 mins

View and pure functions in Blockchain / Solidity - Deep Dive

Choose your learning style9 modes available
Overview - View and pure functions
What is it?
View and pure functions are special types of functions used in blockchain smart contracts. View functions can read data from the blockchain but cannot change it. Pure functions do not read or change any blockchain data; they only use their input to produce output. Both types help save costs and keep the blockchain secure by avoiding unnecessary changes.
Why it matters
Without view and pure functions, every function call would try to change the blockchain, costing money and slowing down the system. These functions let users check information or do calculations without paying fees or risking unwanted changes. This makes blockchain apps faster, cheaper, and safer for everyone.
Where it fits
Before learning view and pure functions, you should understand basic smart contract functions and how blockchain stores data. After this, you can learn about transaction costs, gas optimization, and security best practices in smart contract development.
Mental Model
Core Idea
View functions read blockchain data without changing it, while pure functions neither read nor change blockchain data, only using inputs to compute results.
Think of it like...
Imagine a library: a view function is like reading a book without taking it out, while a pure function is like solving a math problem on scratch paper without looking at any books.
┌───────────────┐       ┌───────────────┐
│   View Func   │──────▶│ Reads Blockchain│
│ (Read-only)   │       │ No Changes     │
└───────────────┘       └───────────────┘
         │
         │
         ▼
┌───────────────┐       ┌───────────────┐
│  Pure Func    │──────▶│ No Read/Write │
│ (Input→Output)│       │ Uses Inputs    │
└───────────────┘       └───────────────┘
Build-Up - 7 Steps
1
FoundationBasic smart contract functions
🤔
Concept: Learn what a function in a smart contract is and how it interacts with blockchain data.
A smart contract function is a piece of code that runs on the blockchain. It can read data stored on the blockchain or change it. For example, a function might return a stored number or update it to a new value.
Result
You understand that functions can either read or write blockchain data, and that writing data costs gas (money).
Knowing that functions can read or write data sets the stage for understanding why some functions are special and cheaper to run.
2
FoundationGas costs and blockchain state
🤔
Concept: Understand that changing blockchain data costs gas, but reading data does not.
Every time a function changes blockchain data, it uses gas, which costs money. Reading data, however, does not cost gas because it does not change the blockchain state. This difference is important for saving costs.
Result
You realize that avoiding data changes when possible saves money and resources.
Understanding gas costs motivates the use of functions that only read data or do calculations without changing anything.
3
IntermediateView functions: read-only access
🤔Before reading on: do you think view functions can change blockchain data? Commit to your answer.
Concept: View functions can read blockchain data but cannot modify it.
A view function is marked with the keyword 'view' in Solidity. It promises not to change any blockchain data. You can call it without sending a transaction or paying gas. For example, a view function can return the balance of an account.
Result
You can safely call view functions to get data without paying gas or risking changes.
Knowing that view functions guarantee no data changes helps you write safer and cheaper smart contracts.
4
IntermediatePure functions: no blockchain interaction
🤔Before reading on: do you think pure functions can read blockchain data? Commit to your answer.
Concept: Pure functions neither read nor write blockchain data; they only use inputs to compute outputs.
A pure function is marked with the keyword 'pure' in Solidity. It cannot access or modify any blockchain state. It only uses its input parameters to calculate and return a result. For example, a pure function might add two numbers and return the sum.
Result
You can use pure functions for calculations that don't depend on blockchain data, making them very cheap and predictable.
Understanding pure functions helps you separate logic that depends on blockchain data from pure computations.
5
IntermediateCalling view and pure functions
🤔
Concept: Learn how to call view and pure functions and how they behave differently from regular functions.
When you call a view or pure function from outside the blockchain (like a wallet or app), it runs locally without creating a transaction or costing gas. However, calling them from inside a contract still counts as a normal function call and may cost gas if it leads to state changes.
Result
You know when and how to use these functions to save gas and improve performance.
Knowing the difference between external and internal calls prevents unexpected gas costs.
6
AdvancedLimitations and restrictions of view/pure
🤔Before reading on: can a view function call a pure function? Can a pure function call a view function? Commit to your answers.
Concept: Understand the rules about what view and pure functions can call and access.
View functions can call other view or pure functions but cannot call functions that modify state. Pure functions can only call other pure functions. Neither can emit events or create transactions. These restrictions ensure no state changes happen.
Result
You can design your contract functions correctly respecting these rules.
Understanding these restrictions helps avoid compilation errors and unintended state changes.
7
ExpertGas optimization and security with view/pure
🤔Before reading on: do you think marking a function as pure or view affects contract security or gas usage? Commit to your answer.
Concept: Learn how using view and pure functions improves gas efficiency and reduces attack surface.
Marking functions as view or pure lets the compiler and blockchain optimize gas usage. It also signals to users and developers that these functions are safe and side-effect free. Misusing these keywords can cause bugs or security risks if the function actually changes state but is marked view or pure.
Result
You write more efficient and secure smart contracts by correctly using these function types.
Knowing the impact of these keywords on gas and security helps prevent costly mistakes in production.
Under the Hood
At runtime, view and pure functions are executed locally on the node without creating a transaction or changing blockchain state. The Ethereum Virtual Machine (EVM) enforces that view functions do not modify storage and pure functions do not read or write storage. This enforcement happens at compile time and runtime, preventing state changes and ensuring deterministic outputs.
Why designed this way?
These function types were introduced to optimize blockchain interactions by distinguishing between read-only, pure computations and state-changing operations. This separation reduces unnecessary gas costs and improves security by clearly defining function behavior. Alternatives without these distinctions would force all calls to be transactions, increasing cost and complexity.
┌───────────────┐
│ User Calls    │
│ View/Pure Func│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Local Node    │
│ Executes Func │
│ No Tx Created │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ EVM Checks    │
│ Enforce Rules │
│ (No State Mod)│
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do view functions sometimes change blockchain data? Commit yes or no.
Common Belief:View functions can change blockchain data if called by the contract owner.
Tap to reveal reality
Reality:View functions cannot change blockchain data under any circumstances; they are strictly read-only.
Why it matters:Believing view functions can change data leads to security risks and incorrect assumptions about contract behavior.
Quick: Can pure functions read blockchain state like balances? Commit yes or no.
Common Belief:Pure functions can read blockchain data but just don't change it.
Tap to reveal reality
Reality:Pure functions cannot read or write any blockchain state; they only use their input parameters.
Why it matters:Misunderstanding this causes bugs when pure functions try to access state, leading to compilation errors.
Quick: Does calling a view function always cost zero gas? Commit yes or no.
Common Belief:Calling a view function never costs gas, no matter how it's called.
Tap to reveal reality
Reality:Calling a view function externally costs no gas, but calling it internally from a state-changing function does consume gas.
Why it matters:Assuming zero gas cost always can cause unexpected expenses and contract inefficiencies.
Quick: Are view and pure functions just for saving gas? Commit yes or no.
Common Belief:Their only purpose is to reduce gas costs.
Tap to reveal reality
Reality:They also improve contract clarity, security, and help the compiler optimize code.
Why it matters:Ignoring their broader role limits understanding of smart contract design and best practices.
Expert Zone
1
Marking a function as view or pure enables compiler optimizations that can inline code or remove unnecessary storage reads.
2
Pure functions guarantee deterministic outputs, which is critical for testing and formal verification of smart contracts.
3
Incorrectly marking a function as view or pure when it modifies or reads state can cause subtle bugs that are hard to detect.
When NOT to use
Avoid using view or pure for functions that must update or depend on blockchain state. Instead, use regular functions with proper access control. For complex state interactions, consider event-driven or off-chain computations.
Production Patterns
In production, view functions are commonly used for getters and status checks, while pure functions handle calculations like cryptographic hashes or math utilities. Developers combine these with state-changing functions to build efficient, secure contracts.
Connections
Functional programming
View and pure functions relate to pure functions in functional programming that avoid side effects.
Understanding pure functions in blockchain helps grasp side-effect-free programming, improving code predictability and testability.
Database read-only queries
View functions are like read-only database queries that fetch data without modifying it.
Knowing database read-only operations clarifies why view functions are safe and cost-free to call externally.
Mathematical functions
Pure functions resemble mathematical functions that always produce the same output for the same input.
Recognizing this connection helps appreciate the deterministic nature of pure functions in smart contracts.
Common Pitfalls
#1Marking a function as view but modifying state inside it.
Wrong approach:function updateBalance() public view { balance = balance + 1; }
Correct approach:function updateBalance() public { balance = balance + 1; }
Root cause:Misunderstanding that view functions cannot change state leads to compilation errors or unexpected behavior.
#2Trying to read blockchain state inside a pure function.
Wrong approach:function getBalance() public pure returns(uint) { return balance; }
Correct approach:function getBalance() public view returns(uint) { return balance; }
Root cause:Confusing pure with view functions causes errors because pure functions cannot access state variables.
#3Calling a view function internally expecting zero gas cost.
Wrong approach:function doSomething() public { uint x = getBalance(); /* getBalance is view */ }
Correct approach:function doSomething() public { uint x = getBalance(); /* internal call costs gas if doSomething changes state */ }
Root cause:Not realizing internal calls to view functions consume gas if the calling function changes state.
Key Takeaways
View functions read blockchain data without changing it and can be called without gas from outside the blockchain.
Pure functions neither read nor write blockchain data and only use inputs to compute outputs, ensuring deterministic behavior.
Using view and pure functions correctly saves gas, improves security, and clarifies smart contract design.
Misusing these function types leads to errors, unexpected costs, and security risks.
Understanding their restrictions and behavior is essential for writing efficient and reliable blockchain smart contracts.