什么是最好的处理在Java中未被接受的方法参数? [英] What's the best to handle unaccepted method arguments in Java?

查看:229
本文介绍了什么是最好的处理在Java中未被接受的方法参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写方法,比方说,你里面DAO对象之一,你不希望这个方法接受某些输入,讨论的缘故,说不允许空参数。你如何去实现的是,考虑到这种方法可能通过新的团队成员在未来不会再使用。

When writing a method, say, inside one of your DAO objects, and you dont want this method to accept certain input, for discussions sake, say it does not allow null arguments. How do you go about implementing that, taking into account this method is likely to be reused in the future by new team members.

我这样做的方式是:


  1. 在接口方面,我是记录一个参数,b和c不能为空的方法的javadoc里面。

  2. 在我检查空值第一件事情,如果任何一个,b或c为空,然后我抛出IllegalArgumentException方法。

但是,如果在未来的某个开发商只是读出方法签名,并决定它他/她需要什么,并开始使用它,而不注意这个细节,更糟的是测试没有透露它。空指针异常不会发生,我们得到一个有用的错误消息,但我们仍然获得生产可避免的已经错误。

But, what if some developer in the future just reads off the method signature and decides that it what he/she needs and starts using it, without paying attention to this detail, and worse testing does not reveal it. NULL pointer exception won't occur and we are getting a useful error message, but we are still getting an error in production that could've been avoided.

有没有办法在编译时强制执行呢?我怀疑这一点,但什么将是去这样做最安全,最糟糕的开发者,防爆方式?

Is there a way to enforce this at compile time? I doubt it, but what would be the safest and most bad-developer-proof way to go about doing this?

推荐答案

我不认为你可以强制执行此编译的时候,但你肯定可以使方法签名容易理解了。

I don't think you can enforce this compile time, but you can certainly make the method signatures easy to understand.

如果您不采的验证之一添加依赖框架可以使用的 JSR 303 @ NOTNULL 或像<一个类似的工具href=\"http://google-collections.google$c$c.com/svn/trunk/javadoc/com/google/common/base/$p$pconditions.html\"相对=nofollow> preconditions 。

If you don't mine adding a dependency on one of the validations frameworks you can use JSR 303's @NotNull or similar tools like Preconditions.

使用JSR 303,你可以做SUFF,如:

With JSR 303 you can do suff like:

@NotNull
@Size(min = 2, max = 14)
@UpperCase
private String licensePlate;

@NotNull
@NotEmpty
public String foo(@NotNull @Pattern(regexp="[0-9]") String param) {
   ...
}

有一个看的开始使用JSR 303 Bean验证了解COM prehensive例子。

Have a look at the Getting started with JSR 303 Bean Validation for more comprehensive examples.

这篇关于什么是最好的处理在Java中未被接受的方法参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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