合同与例外
假设我有以下代码:
public class MainClass {
public static void main(String[] args) {
System.out.println(sumNumbers(10, 10));
}
//@requires a >= 10;
//@ensures \result < 0;
public static int sumNumbers(int a, int b) {
return a+b;
}
}
我可以在这里做两件事:
使用代码契约(在本例中,是注释中的内容)。当 sumNumbers 运行并且 a < 10、它会立即抛出异常(虽然看起来描述性不太好):
Exception in thread "main" org.jmlspecs.jmlrac.runtime.JMLInternalNormalPostconditionError: by method MainClass.sumNumbers
at MainClass.sumNumbers(MainClass.java:500)
at MainClass.internal$main(MainClass.java:9)
at MainClass.main(MainClass.java:286)
或者...
抛出异常。异常可以按照我想要的那样具有描述性。我还要检查函数的末尾,以查看后置条件是否为真。
您会在这里使用哪个?为什么?
Let's assume I have the following code:
public class MainClass {
public static void main(String[] args) {
System.out.println(sumNumbers(10, 10));
}
//@requires a >= 10;
//@ensures \result < 0;
public static int sumNumbers(int a, int b) {
return a+b;
}
}
I can make 2 things here:
Use Code Contracts (in this case, what is in comments). When sumNumbers is run and a < 10, it will throw immediatly an exception (although it doesn't seem to be very descriptive):
Exception in thread "main" org.jmlspecs.jmlrac.runtime.JMLInternalNormalPostconditionError: by method MainClass.sumNumbers
at MainClass.sumNumbers(MainClass.java:500)
at MainClass.internal$main(MainClass.java:9)
at MainClass.main(MainClass.java:286)
or...
Throw an exception. The exception can be as descriptive as I want. I'd also to check in the end of the function to see whenever the post conditions are true or not.
Which would you use here and why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我喜欢代码契约的想法,但描述性的
IllegalArgumentException
(或类似的)为我提示了它。在支持/生产角色(甚至开发)中,获取明确的异常消息会更加清晰,这使您可以在诊断问题所在时取得领先(无论系统是否损坏,或者您在开发过程中是否滥用 API) )。I like the idea of the code contracts, but the descriptive
IllegalArgumentException
(or similar) tips it for me. It's much clearer in a support/production role (or even a development) to get an explicit exception message, which gives you a head start in diagnosis what's going wrong (whether a system is broken, or if you're misusing an API during development).您是否期望在程序正常运行期间可能会向此参数传递无效输入?如果是的话,你能从中恢复吗?
如果是这样,检查异常是可行的方法。
如果你无法从这种情况中恢复过来,那么请务必将其作为合同并大声失败 - 但无论哪种情况,我都会使用描述性错误消息。
Do you expect that invalid inputs might be passed to this argument during normal operation of your program? If they are, can you recover from it?
If so, checked exceptions are the way to go.
If you can't recover from this sort of case, then by all means make it a contract and fail loudly - but in either case I would use a descriptive error message.