Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question
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? –  Brian Knoblauch Dec 22 '11 at 21:24

4 Answers 4

up vote 2 down vote accepted

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.

share|improve this answer
    
This looks like exactly the kind of thing I was looking for. Thanks! –  Sam Goldberg Dec 22 '11 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 '11 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. –  Kevin McCormick Dec 24 '11 at 3:07

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)

share|improve this answer

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.

share|improve this answer
    
This looks interesting, maybe useful for other things we are doing. –  Sam Goldberg Dec 22 '11 at 22:44

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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