0

I know that NULL check for every arguments in a public API is good practice in java. But just curious, do we need do such NULL check in the front of all methods. There are definitely values for doing this: catching error earlier and providing better error message. But is it worthy, I mean doing the same NULL check in all methods seems too tedious. If that is needed, why JVM cannot the job by default.

Please share your thoughts.

Alfred
  • 1,709
  • 8
  • 23
  • 38
  • Best practice: avoid `null`. If it exist, check early then guarantee that it can't happen further down the line, i.e. avoid again. – zapl Dec 19 '13 at 22:40
  • 1
    It does, and when it finds a null, throws an NPE. The JVM can't figure out your *intent*. – Dave Newton Dec 19 '13 at 22:40
  • 1
    Check for nulls if they can cause damage before they trigger a NPE, or if null is a *legitimate value* that you simply don't want to try and call methods on, or if you can say something more helpful than a NPE will. Otherwise, eh. Let Java throw the exception that's *made* for saying "hey, dummy, there shouldn't be a null here!" – cHao Dec 19 '13 at 22:41

2 Answers2

4

If that is needed, why JVM cannot the job by default.

It does! It checks if the value is null, and if not, throws a NullPointerException. In many cases this is the appropriate behaviour and you do not need to change it.

Robin Green
  • 32,079
  • 16
  • 104
  • 187
0

Normally it's easiest to simply declare variables or methods so that they never return a null. However, sometimes it's unavoidable, like in some existing methods in the API, and some self-created methods and variables need to have a null value set. Personally I recommend avoiding null values whenever possible--it's always best to declare a variable from the start, or have a method return, for example, a -1 instead of a null if a certain operation fails. In general though, if you know a variable or method may have a null value, you should do a null check at the beginning just to be on the safe side.

Hope this helps, and I wish you the best of luck!

DerStrom8
  • 1,311
  • 2
  • 23
  • 45
  • 1
    -1 is even worse than null, in most cases. At least with null, it's likely to eventually cause an exception if the caller doesn't account for failure. It's usually better to throw an exception yourself, though, than to count on the caller to check for errors. – cHao Dec 19 '13 at 22:47
  • Had not thought of that, that's a good point. It's much easier to trace a problem with a null than a -1. Thank you for that, @cHao – DerStrom8 Dec 19 '13 at 22:50