RareSkills Solidity Interview Question #29 Answered: What does a modifier do?
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:
- Github: https://github.com/FaybianB
- LinkedIn: https://www.linkedin.com/in/faybianbyrd/
Previous articles:
- Question #19 (Easy): What is the difference between fallback and receive?
- Question #20 (Easy): What is reentrancy?
- Question #21 (Easy): As of the Shanghai upgrade, what is the gas limit per block?
- Question #22 (Easy): What prevents infinite loops from running forever?
- Question #23 (Easy): What is the difference between tx.origin and msg.sender?
- Question #24 (Easy): How do you send Ether to a contract that does not have payable functions, or a receive or fallback?
- Question #25 (Easy): What is the difference between view and pure?
- Question #26 (Easy): What is the difference between transferFrom and safeTransferFrom in ERC721?
- Question #27 (Easy): How can an ERC1155 token be made into a non-fungible token?
- Question #28 (Easy): What is access control and why is it important?
Disclosure: Some content may have been generated with the help of artificial intelligence.