我在Clojure中有一组数字函数,我想验证参数.函数期望有许多类型的参数,例如正整数,百分比,数字序列,非零数字序列等.我可以通过以下方式验证任何单个函数的参数:
Larry Hunter的一些Lisp代码是#3的一个很好的例子.(寻找test-variables宏.)
我的直觉是宏更合适,因为对评估的控制和编译时计算的潜力,而不是在运行时完成所有操作.但是,我没有遇到我正在编写的代码似乎需要它的用例.我想知道编写这样一个宏是否值得付出努力.
有什么建议?
以下是实现此目标的典型方法:
public void myContractualMethod(final String x, final Set<String> y) {
if ((x == null) || (x.isEmpty())) {
throw new IllegalArgumentException("x cannot be null or empty");
}
if (y == null) {
throw new IllegalArgumentException("y cannot be null");
}
// Now I can actually start writing purposeful
// code to accomplish the goal of this method
Run Code Online (Sandbox Code Playgroud)
我认为这个解决方案很难看.您的方法很快就会填充样板代码来检查有效的输入参数契约,从而模糊了方法的核心.
这是我想要的:
public void myContractualMethod(@NotNull @NotEmpty final String x, @NotNull final Set<String> y) {
// Now I have a clean method body that isn't obscured …Run Code Online (Sandbox Code Playgroud)