RareSkills Solidity Interview Question #29 Answered: What does a modifier do?

Faybian Byrd
Coinmonks
Published in
2 min readFeb 23, 2024

--

This series will provide answers to the list of Solidity interview questions that were published by RareSkills..

Question #29 (Easy): What does a modifier do?

Answer: A modifier executes code before and/or after the modified function’s logic is executed. When a modifier is specified on a function, it is invoked when the function is called and passes execution control to the function where _; is found. Modifiers are commonly used as access control mechanisms and allow for precondition and postcondition checks.

Demonstration:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

// SimpleAccessControl demonstrates basic access control mechanisms
contract SimpleAccessControl {
address public owner;

// Modifier to restrict function access to the contract's owner
modifier onlyOwner() {
// This check will run before the `changeOwner` logic is executed
require(msg.sender == owner, "Caller is not the owner");

// This will execute the `changeOwner` logic.
_;
}

// Constructor sets the deploying address as the contract's owner
constructor() {
owner = msg.sender;
}

// Function to change the owner, restricted to the current owner
function changeOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
}

Further Discussion:

The _; syntax in a Solidity modifier is a placeholder that represents the point at which the modified function’s code is executed. For instance, if _; is placed at the beginning of a modifier, the function’s code runs before any other code in the modifier. If _; is placed at the end, the modifier’s code will run before the function’s code.

Connect with me:

Previous articles:

Disclosure: Some content may have been generated with the help of artificial intelligence.

--

--

Faybian Byrd
Coinmonks

Senior Software Engineer, Full Stack/Frontend @Opentensor Foundation | Graduate - Advanced Solidity Bootcamp @ RareSkills. | Certified Solidity Developer (CSD)