1

So let's assume the following code:

modifier Owner() {
    if (msg.sender == owner) _; 
}
function uploadContent() external Owner {

   uploadContent() ..
}

Why not use this?

function checkOwner() internal {
   require(msg.sener == owner, "Youre not the owner");
}

function uploadContent() external Owner {
     checkOwner()
     uploadContent() ...
}

Whats the difference? Is it cheaper in terms of gas cost? Because I dont see any reason why to use the first approach?

1
  • So, its just preference?
    – redigaffi
    Mar 29, 2021 at 19:28

1 Answer 1

4

A modifier can do stuff at the start and at the end and share a variable

A real world example from 1inch contract

modifier discountGST {
    uint256 gasStart = gasleft();

    _;

    uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
    gst.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41130);
}

It can be implemented with a function but it will not be as elegant as using a modifier. If you have to repeat it for several times it will be worse.

I agree with you that some uses it doesn't improve code clarity (using it for requires) and sometimes it can add complexity (multiple inheritance and hierarchies).

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