关于如何控制逻辑流程短路或运行所有逻辑的建议
温馨提示:
本文最后更新于 2024年04月12日,已超过 37 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我。
I am writing in Java and I had a existing code that have bunch of condition checking. The method will return immediately if one of the condition is fail. The existing code looks like this
public Reason checkCondition(){
if (! matchConditionA()) {
return new Reason("Condition A", false);
}
if (! matchConditionB()) {
return new Reason("Condition B", false);
}
if (! matchConditionC()) {
return new Reason("Condition C", false);
}
return new Reason("Match all", true);
}
I would like to add a boolean flag to control the flow of logic checking. Whenever the flag is true, I would like to run all the condition checking any way and return a set of failing reason. The following code is something I can think of.
public List<Reason> checkCondition(String paramA, boolean runAll){
List<Reason> result = new ArrayList<Reason>();
if (! matchConditionA()) {
result.add(new Reason("Condition A", false));
if (!runAll) {
return result;
}
}
if (! matchConditionB()) {
result.add(new Reason("Condition B", false));
if (!runAll) {
return result;
}
}
if (! matchConditionC()) {
result.add(new Reason("Condition C", false));
if (!runAll) {
return result;
}
}
return result;
}
My question is, are there any better way , or design pattern I could use, to reduce the additional if (!runAll)
in all the existing if block?
正文到此结束
- 本文标签: 家庭宠物
- 本文链接: https://www.coder6.net/article/2137
- 版权声明: 本文由蚂蚁原创发布,转载请遵循《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权
热门推荐
-
浏览(166) 评论(0)