2

Should I check for passing of null values for values that need to be valid in constructors? In other words, should I have the class throw when it gets an invalid value, or should I let it be until it tries to do something with it, letting the runtime raise the exception?

I suppose if passing a null value is an error, I should treat it as such in the constructor?

alexgolec
  • 26,898
  • 33
  • 107
  • 159

5 Answers5

8

See this StackOverflow post and the notes on the Fail Early Principle. If passing a null value is an error, you should definitely treat it as such in the constructor.

Community
  • 1
  • 1
Marty
  • 7,464
  • 1
  • 31
  • 52
  • 3
    In addition to fail early, you should also think of it from the standpoint of being self consistent. If the object would be in an inconsistent state once constructed from a null, then by all means, do NOT allow the construction to occur. It is the Class' job to ensure that the object remain self consistent at all times. If all of your objects are self consistent at all times, you have gone a long way to having a stable, predictable code base. – rfeak Jan 05 '11 at 00:23
4

I do. If having a non-null argument is part of your contract, by all means inform the user with an IllegalArgumentException or assert.

I opt for the "minimum surprise" way.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • `NullPointerException` would be more appropriate. And assert is mostly just for debugging purposes. – Peter C Jan 05 '11 at 00:11
  • 2
    I think IllegalArgumentException is just as valid. – Bnjmn Jan 05 '11 at 00:16
  • Since null is an illegal argument it would be just fine, but NullPointerException is more specific. – Peter C Jan 05 '11 at 00:29
  • 1
    No, I tend to use IAE, not NPE. The latter is misleading - it hasn't been dereferenced. – duffymo Jan 05 '11 at 01:14
  • IllegalArgument is the most descriptive. You're saying: hey, null is not allowed here. Also IllegalArgument is usually used to indicate a contract breach, nullpointer is not. – Joeri Hendrickx Jan 05 '11 at 08:25
0

if there is no way to proceed without the error when a null i spassed, then catch it early in the constructor.

if you can do something anyway, then wait.

Randy
  • 16,480
  • 1
  • 37
  • 55
0

I agree with duffymo in general, but it would also depend on when exactly you needed to use that potentially null value. If it's needed in the constructor, then yes you should throw an IllegalArgumentException there. If, however, the value isn't needed until later on (in another method, for example) then you can (and probably should) defer the null check until that point.

Stewart Murrie
  • 1,319
  • 7
  • 12
0

Basic rule: If your constructor cannot guarantee an stable and valid state with the parameters given, throw an Exception!

So, if you need the value to be != null to have a valid object state, check and throw the Exception right away. When else would you do it?

foo
  • 1,968
  • 1
  • 23
  • 35