Solidity Modifiers – Are They Good or Bad for Contract Design?

contract-designcontract-developmentmodifierssoliditystack

I've heard arguments both for and against Solidity modifiers.

On the one hand, they make the code very readable, and the intents behind the calls are very clear. On the other, they increase the overall contract size, as the function code is actually inserted inline in place of the _ keyword (as opposed to just calling the function code). Furthermore, since the code is inlined, both the function and the modifier share the same restricted variable stack, which can lead to a Stack Too Deep error if more than a combined total of 16 variables are used.

What do you guys think? Are you with or against the use of modifiers in your code?

Best Answer

I often find I want a software client to be able to check but I also want a modifier for readability, so it often ends up like this:

modifier onlyIfAllowed() {
  require(isAllowed(args));
  _;
}

function isAllowed() public view returns(bool allowed) {
  allowed = ...
}

function safer() public onlyIfAllowed ... 

Of course, it would also be fine to do that in-line.

function inline() public {
  require(isAllowed());
  // carry on

Ultimately, it is a matter of personal preference. I find it more readable to go like this:

function tricky() public onlyOwner onlyIfAllowed onlySomethingElse { ...

... so the actual purpose of the function doesn't get mixed up with repetitive steps. It's more DRY, in my opinion. Not everyone agrees. The Vyper team, for example, consider modifiers an anti-feature that obscures important logic that they feel should be in-line.

Hope it helps.

Related Topic