Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top