java - When to use @Contract("null -> fail") and when to use @NotNull -


with intellij annotations, it's possible declare failure of function in case of method parameter being null in 2 different ways (and combining them, makes 3 in total):

i can use @notnull annotation on method parameter declare parameter should never null.

@notnull public static string dosomething(@notnull charsequence parameter) throws nullpointerexception {     return string.format("this value: %s, of type %s",             objects.requirenonnull(parameter),             parameter.getclass().getname()); } 

alternatively, can use @contract("null -> fail") annotation, declares if first parameter null, method throw exception.

@notnull @contract("null -> fail") public static string dosomething(charsequence parameter) throws nullpointerexception {     return string.format("this value: %s, of type %s",             objects.requirenonnull(parameter),             parameter.getclass().getname()); } 

lastly, can use both , nothing in intellij idea 14.1.4 complaining:

@notnull @contract("null -> fail") public static string dosomething(@notnull charsequence parameter) throws nullpointerexception {     return string.format("this value: %s, of type %s",             objects.requirenonnull(parameter),             parameter.getclass().getname()); } 

which of these 3 cases best use?

in case, i'd use @notnull, because:

  • it's more specific annotation , idea able produce more specific warnings based on it
  • idea can generate runtime assertions ensuring it's not null

@contract annotation more powerful less specific tool. allows express more complex contracts downsides resulting editor warnings might more obscure, , there no runtime checks added automatically.


Comments