Từ khóa modifier giúp định nghĩa các function modifier. Một số tính chất của function modifier:

  • Các function modifiers không thể được gọi thực thi như một hàm thông thường mà chỉ có thể gắn vào các hàm khác.
  • Các hàm có function modifier sẽ thực thi function modifier trước khi thực thi các câu lệnh trong thân hàm.
  • Function modifier thường được dùng để kiểm tra một số điều kiện trước khi thực hiện hàm gốc.

Việc sử dụng các function modifier nằm trong một mô hình lập trình có tên là Condition-Oriented Programming (COP). Mục đích của COP là giảm thiểu các câu điều kiện ở trong thân hàm1.

Ví dụ:

modifier onlyOwner() {
	require(msg.sender == owner, "Not owner");
	_;
}

Minh họa:

Function modifer cũng có thể nhận đối số. Ví dụ:

// A mapping to store a user's age:
mapping (uint => uint) public age;
 
// Modifier that requires this user to be older than a certain age:
modifier olderThan(uint _age, uint _userId) {
	require(age[_userId] >= _age);
	_;
}
 
// Must be older than 16 to drive a car (in the US, at least).
// We can call the `olderThan` modifier with arguments like so:
function driveCar(uint _userId) public olderThan(16, _userId) {
	// Some function logic
}

Footnotes

  1. tham khảo Smart Contracts - Security Patterns in the Ethereum Ecosystem and Solidity