是否有一种美妙的方式来断言Java方法中的前提条件? [英] Is there an beautiful way to assert pre-conditions in Java methods?

查看:116
本文介绍了是否有一种美妙的方式来断言Java方法中的前提条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的很多函数都在声明之下有一整堆验证代码:

A lot of my functions have a whole load of validation code just below the declarations:

if ( ! (start < end) ) {
    throw new IllegalStateException( "Start must be before end." );
    }

我想精确指定某些输入的有效范围 - 例如a A> B,C =>
1或str_d.length()> 0.

I'd like to precisly specify the valid ranges of certain inputs - for example a A > B, C => 1 or str_d.length() > 0.

鉴于我的一些函数有很多参数,必须经过验证我最终可能会编写大量的锅炉板来验证前置条件。我正在编写一个主要由非技术开发人员使用的库,我们发现验证函数输入是帮助我们的用户正确操作API的最佳方法。我们越早提出错误,客户就越不需要做的工作。

Given that some of my functions have quite a lot of arguments which must be validated I can end up writing a lot of boiler-plate just to validate the pre-conditions. I'm writing a library which is mainly going to be used by non-technical developers, we've found that validating function inputs is the best way to help our users operate our API correctly. The sooner we raise an error the less work our customers will have to do.

是否有一种更优雅的方法来指定前置条件,后期条件(以及可能的条件)在我的方法中的不变条件。

Is there a more elegant method to specify the pre-conditions, post-condtions (and possibly the invariant conditions) in my methods.

一位同事告诉我有关Eiffel编程语言的一个功能,它允许以非常自然的方式描述前/后/不变条件,而无需重复大量的样板代码。是否有Java语言的附加组件,这将允许我使用这些魔术?

A colleague told me about a feature of the Eiffel programming language which allows pre/post/invariant conditions to be described in very natural ways without repeating a lot of boilerplate code. Is there an add-on to the Java language which will allow me to use some of this magic?

推荐答案

番石榴前置条件 class就是为了这个。您通常将它与静态导入一起使用,因此您的示例如下所示:

Guava's Preconditions class is just for this. You typically use it with static imports, so your example would look like:

checkArgument(start < end, "Start must be before end");

它还可以轻松地向消息添加更多信息,而无需支付 String 如果检查通过则连接。

It makes it easy to add more information to the message as well, without paying the cost of String concatenation if the check passes.

checkArgument(start < end, "Start (%s) must be before end (%s)", start, end);

断言语句不同,这些不能被禁用。

Unlike assert statements, these can't be disabled.

这篇关于是否有一种美妙的方式来断言Java方法中的前提条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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