What is modifier in smart contract
Solidity Modifier is used to automatically check conditions or change the behavior before executing smart contract. So custom software development company uses modifier to increase performance of blockchain contracts
Modifier is also inheritable properties of smart contracts and overridden by parent smart contracts.For an example, in Division operation number can not be divided by 0. So in our contract, we check that second number is grater than or not equal to 0. then syntax looks like this.
modifier name(){ …. }
In our example, notzero checks modifier for division operation is given below.
modifier notZero(uint a){
if(a == 0){
throw;
}
_;
}
Here _ represent continue with next execution. We add this modifier to our solidity getDivision function so our function will check notzero condition before giving result.
function getDivision(uint a, uint b) constant notZero(b) returns (uint) {
return a / b;
}
So our final Solidity Smart Contract looks like this.
pragma solidity ^0.4.15;
contract Mathematics {
uint rate;
event InterestSet(uint a);
modifier notZero(uint a){
if(a == 0){
throw;
}
_;
}
function getSum(uint a, uint b) constant returns (uint) {
return a + b;
}
function getSub(uint a, uint b) constant returns (uint) {
return a - b;
}
function getMultiplication(uint a, uint b) constant returns (uint) {
return a * b;
}
function getDivision(uint a, uint b) constant notZero(b) returns (uint) {
return a / b;
}
function setInterest(uint a) notZero(a){
rate = a;
InterestSet(rate);
}
function getSimpleInterest(uint amount, uint month) constant notZero(amount) notZero(month) returns(uint){
return (amount * month * rate)/100;
}
}
Now we can deploy this contract in parity or using truffle to check how it works. This is very basic contract to get started with solidity. We will show you this in our next blog how to deploy solidity contracts in parity and truffle. Until you can check more contacts example at solidity-by-example.