1

I've seen this piece of code several times on Stackoverflow:

public void doStuff(Object anObject) {  
    if (anObject == null) {  
        throw new NullPointerException("anObject can't be null");   
    }  
    //rest of the function
}

This is a guard clause against null parameters because passing null to a function that requires the argument to be non null will result in a NullPointerException.

I understand the importance of guard conditions to validate arguments in other cases (i.e. checking date ranges, negative monetary values, invalid string size etc.).

However, in the case of null specifically isn't throwing a NullPointerException redundant? How does that differ from letting the Run-time throw a NullPointerException itself later on?

Note: I'm asking in a language agnostic way since the pattern itself could be applied in both Java and C#.

Yirkha
  • 12,737
  • 5
  • 38
  • 53
Songo
  • 5,618
  • 8
  • 58
  • 96
  • 2
    A better alternative is `InvalidArgumentException` – SamTebbs33 May 12 '16 at 21:41
  • 3
    Maybe to avoid side effects. If the parameter isn't referenced until half way down the method and that method has already done some non-reversible work it might be better to check it before any damage is done? – OldBoyCoder May 12 '16 at 21:42
  • 1
    Personally, you should be throwing an `IllegalArgumentException` in Java. You do this preemptively. In certain cases, you won't immediately use `anObject`, you might initialize some other objects, do some other processing, then use it. Throwing right away prevents all of that from happening uselessly. – Sotirios Delimanolis May 12 '16 at 21:42
  • difference? suppose the function doesn't have that check and the code does somethin irreversible before the null exception... Also, the usual is not `NullPointerException` but `NullReferenceException` – Gusman May 12 '16 at 21:42
  • @Gusman this has the `java` tag as well. – shmosel May 12 '16 at 21:43
  • Everyone is assuming this is a c# question, but the question is tagged with both `java` and `c#`, and the example is in Java. – shmosel May 12 '16 at 21:44
  • @shmosel And the C# one too... XD let's just agree the question doesn't make any sense and not start a bunch of comments on who is right as we both are ;) – Gusman May 12 '16 at 21:45
  • The _real_ question is: Why `NullPointerException` in Java? We all know _Java doesn't have pointers!_ Isn't that why it is so superior to C++ and other benighted languages? So what the heck does `NullPointerException` mean anyway, huh? (P.S. I already know the answer, and it has to do with propaganda, not technical merits.) – davidbak May 12 '16 at 21:59
  • "fail fast" is a good answer, but there's another reason: Documentation. That `if` statement isn't just for the compiler: It declares that `anobject!=null` is a _precondition_ of the method. The top of the function declaration is where any programmer is going to look to see if any such preconditions are declared. – Solomon Slow May 12 '16 at 22:04
  • @jameslarge - especially true if you use Guava Preconditions or some other similar library where the method name itself is documentation (i.e., you don't need to mentally parse a `if (foo != null) throw ...` statement). – davidbak May 12 '16 at 22:26

3 Answers3

7

Since this question has C# tag, I'll answer about C# case. In this case, what is thrown when you access null pointer is NullReferenceException, and what is usually thrown when argument is null is ArgumentNullException. But what is more impotant is that when you check argument explicitly, you:

  1. Throw exception as soon as possible, not somewhere in the middle of the method when you suddenly access null pointer.
  2. You are saying explicitly what is null. In C# at least when NullReferenceException is throw you are left guessing what exactly was null and where.
Evk
  • 98,527
  • 8
  • 141
  • 191
4

The only difference is when it happens. It may sometimes be desirable for an exception to be thrown early, before the code starts modifying state in ways that might be invalid if the exception is thrown in the middle. That said, it seems like bad practice to throw a NullPointerException; it would be better to throw an IllegalArgumentException. Edit: according to comments below, NullPointerException is the recommended exception to throw in this case, at least for Java.

adv12
  • 8,443
  • 2
  • 24
  • 48
  • 3
    Effective Java does specify the convention of throwing an NPE in this case. – Lee May 12 '16 at 21:43
  • 1
    Also note Guava's `Preconditions.checkNotNull()` throws an NPE. – shmosel May 12 '16 at 21:47
  • 1
    Link supporting comment by @Lee: [IllegalArgumentException or NullPointerException for a null parameter?](http://stackoverflow.com/a/8160/5221149) – Andreas May 12 '16 at 21:49
1

This helps in detecting the error as soon as possible. The method might not throw a null pointer exception (depending on the logic of the code) and the null object might propagate elsewhere in other methods/code and throw the exception there, or worse it could cause false results thus resulting in a silent bug that might make it into the final code...

Extracted from Effective Java Second Edition

If an invalid parameter value is passed to a method and the method checks its parameters before execution, it will fail quickly and cleanly with an appropriate exception. If the method fails to check its parameters, several things could happen. The method could fail with a confusing exception in the midst of processing. Worse, the method could return normally but silently compute the wrong result. Worst of all, the method could return normally but leave some object in a compromised state, causing an error at some unrelated point in the code at some undetermined time in the future.

Youssef Lahoud
  • 529
  • 3
  • 8