什么是流量控制异常的替代方法? [英] What is an alternative to exceptions for flow control?

查看:167
本文介绍了什么是流量控制异常的替代方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继承了一个处理请求的java应用程序,如果确定一个请求应该被取消,那么它将抛出一个异常。异常对于以前的开发人员来说是方便的,因为它们是一种简单的方法,可以退出不再适用的逻辑树(yes goto),并将堆栈跟踪打印到具有良好信息的日志中。这似乎是论坛和博客上的异常,不应该将流程控制用于异常处理,而超过一半的请求被取消,所以它们绝对不是特殊情况。一个理由是表现,这不适用,因为我们的异常代码运行速度足够多年。另一个论点是,我同意的这个意见不清楚。我的问题是:有什么办法我唯一可以想到的是,如果处理应该继续,否则每个方法都返回true,否则返回false。这似乎会使我的代码变大这么大:

I inherited a java application that processes requests and throws an exception if it determines a request should be cancelled. Exceptions have been convenient for the previous developer because they are an easy way to exit out of a tree of logic that no longer applies (yes a goto) and it prints a stack trace to the log which is good info to have. It seems to be the consenus on forums and blogs that exceptions should not be used for flow control and over half of the requests processed are cancelled, so they're definitely not exceptional situations. One argument is performance, which doesn't apply because our exception-ful code has run fast enough for years. Another argument is that the goto-ness of it is not clear, which I agree with. My question is: What is the alternative. The only thing I can think of is to have every method return true if processing should continue or false if it shouldn't. This seems like it would hugely bloat my code changing this:

checkSomething();
checkSomethingElse();

进入:

boolean continueProcessing = false;
continueProcessing = checkSomething();
if (!continueProcessing) {
    return false;
}
continueProcessing = checkSomethingElse();
if (!continueProcessing) {
    return false;
}

然后如果方法应该返回什么?任何指导都会很好。我真的很想观察任何最佳做法可用。

And then what if the method is supposed to return something? Any guidance would be great. I'd really like to observe whatever "best practices" are available.

更新:

另一点我可能应该首先提到的是,请求被取消超过50%的时间,并不意味着没有正确的事情,这意味着毕竟不需要请求。

Another bit I probably should have mentioned in the first place is that a request is cancelled more than 50% of the time and does not mean something didn't go right, it means the request wasn't needed after all.

推荐答案

请参阅多慢Java异常?有关这个主题的很好的讨论。

See How slow are Java exceptions? for a great discussion on this topic.

这篇关于什么是流量控制异常的替代方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆