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

血红的双手。 提交于 2019-12-08 09:49:29

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.

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

  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.

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