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

查看:39
本文介绍了在 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. 在接口中,我在方法 javadoc 中记录了参数 a、b 和 c 不能为空.
  2. 在方法内部,我首先检查空值,如果 a、b 或 c 中的任何一个为空,则抛出 IllegalArgumentException.

但是,如果将来的某个开发人员只是读取方法签名并决定他/她需要什么并开始使用它,而不注意这个细节,并且更糟糕的测试没有揭示它呢?NULL 指针异常不会发生,我们收到了有用的错误消息,但我们仍然在生产中收到本可以避免的错误.

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 或类似的工具,例如 先决条件.

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,您可以执行以下操作:

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 验证,了解更全面的示例.

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

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

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