Solidity Functions: Constant vs View vs Pure

Function modifier differences explained.

By Ron Gierlach

As of Solc 0.4.17, two new function modifiers have been introduced in lieu of constant -- they are view and pure. These are exciting additions that offer us the chance to write more expressive contracts.

Previously, functions marked constant were functions that did not change any state values of a contract. By marking them as such, the compiler could know that storage data would not be written as a result of the function call and consequently no network verification would be required. No transaction to mine, meant no gas needed to be spent -- just read that data right off the blockchain! These functions were essentially look-ups for data held in or derived from a contract's state.

However, the term "constant", already being used to mark variables as read-only, was too vague to communicate such intent. It has been deprecated in favor of the more accurately named view modifier. After all, what we are asking when we call these functions is to view some data on the blockchain.

The pure modifier comes from the functional programmer's vernacular. In FP, to describe a function as "pure" is to say all the data the function is concerned with is either passed in or defined in its scope. So it should stand as no surprise that pure functions in Solidity are not allowed to even read (let alone write) storage data. What's the benefit in this you might wonder? Well a lot actually, pure functions retain view's transaction-free benefits and are great for internal helpers and utilities relating to tasks like calculation, permission, and typecasting.

I hope I've cleared the air on these new modifiers and have encouraged the writing of safer, more expressive contracts. For more information you can refer to the official docs.

Now get coding!