What's the best to handle unaccepted method arguments in Java?

徘徊边缘 提交于 2019-12-23 03:31:11

问题


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.

The way I do it is:

  1. In the interface, I document inside the method javadoc that arguments a, b and c cannot be null.
  2. Inside the method I check for null values first thing, and if any of a, b or c are null then I throw an 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?


回答1:


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

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.

With JSR 303 you can do suff like:

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

or

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

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




回答2:


You can use jsr305 with static code check tools like findbugs to check it before commit/release.

public String method(@NonNull String parameter ){
   ...
}

findbugs manual on annotation




回答3:


  1. As closest as you can get in enforcing things at compile time is by throwing checked exceptions which will force the caller to handle the exception at compile time. This might make them read the doc. The IllegalArgumentException is unchecked and can go unnoticed.

  2. Normal practice in safeguarding on unusable values is by returning at the point we identify something unusable and add an error message for display. This will prevent the exception on production that might happen if the execution continued in that method, but might not altogether avoid it.



来源:https://stackoverflow.com/questions/9545308/whats-the-best-to-handle-unaccepted-method-arguments-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!