In solidity use of require and assert is recommended than using if else conditions but in every solidity example where modifiers are used instead of require if else is used. So is it Okay to use if else in modifiers.
1 Answer
The difference between:
modifier onlyOwner {
require(msg.sender == owner);
_;
}
and
modifier onlyOwner {
if(msg.sender == owner);
_;
}
is now less significant as of Byzantium, due to the fact that require or assert will actually execute the revert opcode instead of throw, which means remaining gas for any given transaction will now be refunded instead of being used up.
Use of require will also revert any state changes, so you must factor this into your decision.
For example, in the following code, if one was to call eatStuff() - eatOrange() would get called, followed by eatApple(). The modifier checkOrangeStock() verifies there are enough oranges, and we are able to eat one. However, when checkAppleStock() gets executed, the require fails and all state which was changed gets reverted. This means we have to give back the orange we took, which in this case, might not be the intended behaviour.
contract MrHungry {
uint oranges = 2;
uint apples = 0;
modifier checkOrangeStock() {
require(oranges > 0);
_;
}
modifier checkAppleStock() {
require(apples > 0);
_;
}
function eatStuff() public {
eatOranges();
eatApples();
}
function eatOranges() private checkOrangeStock {
oranges--;
}
function eatApples() private checkAppleStock {
apples--;
}
}
If we were to use an if conditional in the modifier for eatOrange() instead of require, our state would not have been reverted and our hunger for delicious fruit may at least be partially satisfied.