Search code examples
javaminecraftbukkit

Is it ok to use assert on a field I know won't be null?


From reading existing posts I have come to learn that "assert" should not be used in production code, however IntelliJ's first tip for me when using a method I know won't be NULL, but is still Nullable in other ways, is to tell me that I should use "assert" IntelliJ screenshot of tooltip

In the above code ItemMeta will not be null when creating a new ItemStack however it can be null if ItemStack is also null, which is why it doesn't have the @NotNull annotation to begin with.

Knowing this, what is the most correct way to handle this Warning? Is it to ignore it because I know it will never be null, or is it to still do a null check. If it is to do a null check which kind, assert or the way I was doing already which is

if(fillerMeta != null) 

Solution

  • I have come to learn that "assert" should not be used in production code

    That's very debatable. If you're asserting fillerMeta != null, you're saying this can't be null or something is seriously wrong with my code.

    That's perfectly fine. But you need to be careful if you want to assert something, or error handle something. Asserting something like 1 + 1 == 2 is fine, because if it turns out math doesn't work that way, all other assumptions you made are probably out of the window too. Thus it's fine for the program to just explode.

    If fillerMeta could be null because it was for example returned from a function you think might return null you should do error handling instead. E.g. if (fillerMeta == null) throw new Exception... and gracefully handle that.