Learn Solidity: Function Modifiers & How They Works

In this post, we will understand what are function modifiers & how to use them in Solidity Language.

Advertisements
World is looking for a Certified Blockchain Expert Become one

Notice: This is one of the multi-post series of Learn Solidity - Build Decentralized Application in Ethereum. This is an attempt to teach you all about Solidity - A Programming Language for Ethereum Based Smart Contracts. If you want to take this as a video course please signup using below button.
pragma solidity 0.4.8; 

/*
* @title Learn Solidity: Function Modifiers in Solidity
* @author Toshendra Sharma
* @notice Example for the Learn Solidity
*/

// Let's talk about one of the most useful feature known as "function modifiers" in solidity
// Modifiers can be used to easily change the behaviour of functions, 
// for example they can be used to to automatically check a condition prior to executing the function. 
// They are inheritable properties of contracts and may be overridden by derived contracts.

// one example use case of function modifiers would be if we want to call the killContract function 
// through only via owner/creator of the contract.



contract FunctionModifiers {

	address public creator;
    // Define consutruct here
    function FunctionModifiers() {
       // Initialize state variables here
       creator = msg.sender;
    }

    //this is how we define the modifiers
    modifier onlyCreator() {
        // if a condition is not met then throw an exception
        if (msg.sender != creator) throw;
        // or else just continue executing the function
        _;
    }

    // this is how we add a modifier to the function 
    // there can be zero of more number of modifiers
    function kill() onlyCreator { 
    	selfdestruct(creator);
    }

}
Previous: Function Calls & Return Types in Solidity Next: Fallback Function in Solidity