简体   繁体   中英

C# Contracts vs NotNull/roll your own in Java

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM