0

Solidity: Function Modifiers.

Function modifiers are a way to extend the behavior of functions and this is usually utilized to apply or enforce some required restrictions. The restrictions enforced by the modifier may be required in different locations of the logic, so having the modifier defined independently from the code of the function allows for the restrictions to be applied to any other function that requires it (which helps in avoiding the duplication of code).

Modifiers are similar to how annotations are used in object oriented programming to extend the behavior or apply restrictions to the code definition of functions. You can apply a modifier to a function by including the name of the modifier as part of the function declaration itself.



View

The view function modifier is used to indicate that the function in no way will alter the state of the storage, that is, it will not write anything, it will work as a read-only function.

 contract fooContract {
    bool isFoo;

    function fooFunction() public view returns (bool) {
        return isFoo;
    }
}

In the above example, the modified function will simply return a value.



Pure

The pure modifier states that we are dealing with a pure function, that is, a function that only concerns itself with whatever parameters were passed into it and whatever variables are declared in the scope of the function. They do not modify or even read any state or storage variable.

 contract fooContract {
    using SafeMath for uint256;

    function fooFunction(uint256 val1, uint256 val2) public pure returns (uint256) {
        return va1.add(val2);
    }
}

In the above example, the function will use received parameters to calculate and return the result.



Custom Modifiers

Programmers can also extend the behavior of a function using modifiers created by themselves and in general they are used to enforce custom restrictions to the logic of a function. In the below example we can see that the function fooFunction uses the fooModifier:

contract fooContract {
    bool flag;

    modifier fooModifier () {
        require(flag == true);
        _;
    }
    
    function fooFunction() public fooModifier {
        //Function logic
    }
}

Analyzing the above code, one of the first question that comes to mind is: what code is executed first? The code in the modifier or the code in the function? This is where “_;” (line 6 on the above example) comes into play, this statement represents when in the logic the code of the function will be executed.

In the above example, “_;” is used after the require, meaning that the code of functions using this modifier will be executed after the require statement. In other words, “_;” represents the location of the function code within the logic.



<< Prev

Next >>