1

I would like to reduce redundant and verbose null checks in Java , but I understand Java does not have a standard @NotNull annotation where as c# has contracts that can be used, such as

Contract.Requires( x != null );

I might be missing something, but couldn't I just code my own?

public class Contract {

    public static void requireNotNull(Object object) {
        if ( object == null )
           throw new IllegalArgumentException("Contract forbids null");
    }

}

Is this missing any of the benefits of @NotNull or Contracts?

Gonen I
  • 3,718
  • 18
  • 41
  • It seems you need the method to be synchronized – efekctive Feb 11 '17 at 00:42
  • Java has [quite a few `@NonNull` annotations](http://stackoverflow.com/questions/4963300/which-notnull-java-annotation-should-i-use) and the most popular ones should be supported by any decent IDE. Whatever you do, don't roll your own implementation. – Mick Mnemonic Feb 11 '17 at 01:04
  • Pluggable Type System may help you too – efekctive Feb 11 '17 at 01:10

1 Answers1

2

Code Contracts, as opposed to what you wrote in Java, can be analyzed statically and will give a build error if violated. The Java code you wrote will only give a run-time error.

For instance if you mark a parameter on a method as Not Null and then try to call it at a higher layer without performing a null check you will get an error. This is not a compile-time error, as Code Contracts are part of the static analyzer and as such if you are compiling outside of Visual Studio or another product that implements the Code Contract static analyzer it won't get caught.

See this documentation for more details.

Jason Lind
  • 263
  • 1
  • 2
  • 15