0

I'm having a hard time defining for myself what would be the best approach for when to use require and when to use an if statement.

Let's take the following method for sake of example:

function setOwner(address _newOwner) public {
    require(_newOwner != address(0), "cannot set owner to 0");
    owner = _newOwner;
}

Would it make sense to write such a function like so:

function setOwner(address _newOwner) public {
    if (_newOwner != address(0)) {
        owner = _newOwner;
    }
}

Is there real advantages and/or detrements to using either? I can see the argument being made that the require is way more verbose, and helps the end user of the contract understand whats going wrong. Besides this, I would like to know if there's any implications concerning the performance (read: gas fees).

Thanks

1 Answer 1

0

require will stop the call or revert the transaction, the if statement won't. If you are trying to replace require you will have to use revert. So your examples don't serve the same thing and you can't compare them.

to replace require you will need to do something like this :

function setOwner(address _newOwner) public {
    if (_newOwner == address(0)) {
        revert("cannot set owner to 0")
    }
}

and that would make it 2 statements instead of one which would increase the gas cost.

From a functionality perspective, the one of a standard ownership change feature, setOwner should be as elementary as possible so putting more conditions and logic in it would make your contract more hard to read and proof and thus harder to trust. It's better to create another feature that uses _setOwner a private function that simply does the owner address with the null address check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.