链检验器将像下面如何用Java
public class MyClass {
private Integer myField;
private Result result;
// more global variables
public MyResult check(Integer myParameter) {
init(myParameter);
if (myField < 0) {
result.setErrorMessage("My error message");
return result;
}
// a lot more 'checks' like above where something may be written
// to the error message and the result gets returned.
}
private void init(Integer myParameter) {
result = new Result();
result.setExistsAnnouncement(/*search a certain object via crudService with myParameter*/);
// initialize other global variables including myField
}
}
问题一类是上面的check
方法是太长,有许多return
语句。我想到了一些重构,但我仍然不确定要做什么。我在想像一个连锁模式。然后,我会执行几个检查员类,他们或者调用链中的下一个检查器,或者返回result
与相应的errorMessage
。
但是后来我有了一个更好的主意(至少我这么认为):为什么不像java 8那样表现?我想过使用像Try
- Success
- Failure
- 模式。但我不知道如何实现这一点。我想到的是这样的:
entrancePoint.check(firstChecker)
.check(secondChecker)
.check // and so on
的想法是:当check
失败时,它会表现得像Optional.map()
和返回类似的Optional.EMPTY
(或在这方面有点像Failure
)。当check
成功时,它应该继续下一步检查(返回Success
)。
你有这样的经验吗?
我以前做过同样的事情,但没有链接。我做到这一点的方式是1.)创建一个'Checkable'接口,它包含一个方法'check()',它需要抛出一些'CheckFailedException',以及这个接口的一些具体实现。 2.)在'MyClass'中创建'List'变量,并且'MyClass'中的check()遍历每个checkable元素并在其上调用check()。 3.)使用构造函数或setter方法初始化要执行的检查列表(我使用的是spring,所以我是这么做的)。 –
Jay
是的,这可能有效。但我认为那里有更好的解决方案。目前我仍然试图通过Try-Failure-Success-Pattern来完成此项工作,如下所示:https://dzone.com/articles/whats-wrong-java-8-part-iv。区别在于:在链接他们做例外...我使用此尝试成功失败实现btw:https://gist.github.com/mariofusco/8287951 – Chris311
你可以使用Hibernate验证器,如果你在编译时知道约束条件? http://hibernate.org/validator/ –