contract MyContract{
uint value; //Global State Variable
function getValue() view returns (uint){
return value;
}
}
View:
as the name implies we just want to see something, from the above code we just want to see the value of our 'value' in the contract without any computation or editing, so with view we just check for the value of a variable at every point in the blockchain. They do not modify the state of the blockchain.
View functions can read from the state variable but they cannot change the value of the state
contract MyContract{
uint value;
function getValuePlusOne( uint i, j) public pure returns (uint){
return i+j
}
}
Pure:
Pure functions are similar to view the only difference is computation can be done on the values they return. So in the above code we return the value but add an increase of one.
Pure functions promise not to modify or read the states
What if we don't add view
or pure
to our function??
Blockchain automatically see's it as function with which we can modify the value.
contract MyContract{
uint value;
function IncreaseValueByOne() private{
return value++; // We simply increase the value of the global state which is value by 1
}
}
View functions can only call view functions, pure functions can only call pure functions too.
My next article will cover function visibilty which will expand more on private
, public
& external
keywords.