7

After writing my billionth null check in Java code, I started wondering why the ability to null check method arguments wasn't already built in to Java. For example, for some methods, I want to throw an IllegalArgumentException if some (or all) of the arguments are null. It would be great if I could mark up the code, and have the compiler generate the validation which throws an informative Exception if the validation fails.

Is there anything already in Java where you can specify some correctness parameters for method arguments (e.g. int has to be within certain range, or Object has to be not null), and have the Compiler auto-generate the code?

In Java it seems like this should be handled with annotations. (I guess in C/C++ you could define some nice macros to do this for you.) In searching the web on this issue, I saw reference to JSR 305, but this seems targeted toward use with IDE tools, and not with the Java compiler.

I'm guessing this already exists in other programming languages. So I would be interested to hear about how this may work in these languages, as well as what might exist (or be coming up) in Java.

1
  • 1
    The null check feature was originally expected in Java 7 (the syntax was even unofficially published), however it appears to have either been deferred until Java 8 or pulled completely. Anyone know for sure that can share? Dec 22, 2011 at 21:24

4 Answers 4

3

What you're trying to do is sometimes called Designing By Contract. There are a number of frameworks that achieve this goal, and you can define more than just null checks, but most any kind of pre or post condition, too.

A quick Google search shows a few good solutions for Java:

  • Contracts for Java Uses annotations (as you have suggested):

    interface Time {
     ...
    
     @Ensures({
       "result >= 0",
       "result <= 23"
     })
     int getHour();
    
     @Requires({
       "h >= 0",
       "h <= 23"
     })
     @Ensures("getHour() == h")
     void setHour(int h);
    
     ...
    }
    
  • jContractor Uses separate classes

    protected boolean Stack_Precondition (Object [] initialContents) {
        return (initialContents != null) && (initialContents.length > 0);
    }
    

This should get you started.

3
  • This looks like exactly the kind of thing I was looking for. Thanks! Dec 22, 2011 at 22:45
  • How can you know if they are good if you just did a search as opposed to having actually used then?
    – user1249
    Dec 23, 2011 at 8:16
  • I don't know if they're good, any feedback here is certainly welcome. I'm a .NET developer primary and speak volumes about Code Contracts, however. Dec 24, 2011 at 3:07
4

Not in standard Java.

The cleanest syntax in a widely used library is perhaps the one in Google Guava.

public void fullyImplementedGuavaConstructorWouldBe(Long id, String firstName, String lastName, String login) {
        this.id = checkNotNull(id);
        this.firstName = checkNotNull(firstName);
        this.lastName = checkNotNull(lastName);
        this.login = checkNotNull(login);

        checkArgument(firstName.length() > 0);
        checkArgument(lastName.length() > 0);
        checkArgument(login.length() > 0);
    }

(from http://blog.solidcraft.eu/2010/10/googole-guava-v07-examples.html)

Javadoc: http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Preconditions.html#checkNotNull(T, java.lang.Object)

3

JSR-303 - Is the standard for Bean Validation and is supported by Hibernate Validator and several other frameworks. It supports the sort of annotation based range checking and not null checking that I think you're after.

The Bean Validation specification is actually going through an update at the moment, so expect more possibilities in the near future.

1
  • This looks interesting, maybe useful for other things we are doing. Dec 22, 2011 at 22:44
2

If you're using the Spring framework, it's possible to use Assert to handle input checks:

public String modifyString123(String myString) {
    Assert.hasText(myString, "myString can not be null or empty");
    return myString + "123";
}

An IllegalArgumentException will be thrown if the input is null or empty.

1
  • The difference between this and design by contract is huge. With design by contract, you get a compile-time error if myString is null.
    – Bill K
    Jul 18, 2017 at 17:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.