Solidity – Difference Between if and require

solidity

if(_newDelegate != delegateContract){    
    // Do something 
}

require(_newDelegate != delegateContract){
    // Do something 
}

Could anyone explain difference between if and require in solidity? When to use if and require? I taught both are same and can be used alternatively.

Best Answer

if (_newDelegate != delegateContract) {
  // do something
}

is just a conditional execution of the // do something block. So if that condition is not met, the // do something block is skipped. But the execution moves to the next line after that block.

You use require when you wish to revert the entire state changes so far in the function if some condition is not met. For example,

uint256 input;
address sender;

function some_state_changing_fn (uint256 _input) public returns (bool success)
{
  sender = msg.sender;
  require(_input >= 100);
  input = _input;
  success = true;
}

In case _input is less than 100, you don't want even sender to be updated to msg.sender. So when the require fails, the entire transaction is reverted. This may not seem so relevant in the function body above. But there are instances where you call another contract, transfer some tokens, etc. For such situations, the require is an extremely safe way to handle failures or conditions not being met in solidity.

Please refer this: https://solidity.readthedocs.io/en/v0.4.25/control-structures.html?highlight=require#error-handling-assert-require-revert-and-exceptions