重点只有一句:如果你想在函数执行前做一些前置工作如校验,请使用modifier。
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract Test{
modifier MustGreaterThanOne(uint x){
require(x>1,"x must greater than 1");
//下划线可以理解为函数占位符,代表即将执行的函数
_;
}
//先执行MustGreaterThanOne,x大于1才执行increase,否则increase不会执行
function increase(uint x) external MustGreaterThanOne(x) pure returns (uint) {
return x+1;
}
function decrease(uint x) external MustGreaterThanOne(x) pure returns (uint) {
return x-1;
}
}
在面向对象语言如C#之中,如果想实现类似这种AOP的写法,还得自己实现个装饰模式,solidity直接语法层面就支持了,不得不说还是很方便的,例如这种参数校验逻辑,可以抽出来复用,以后如果校验逻辑有变动,只需要改modifier函数就可以了,不必去每个函数对应的地方修改。
