While looking through some old code I came across this gem:
MyObject o = new MyObject("parameter");
if (o == null) o = new MyObject("fallback parameter");
The second line is marked in Eclipse as dead code, and I understand why. No exception seems to be explicitly thrown, and it isn't possible for the MyObject
constructor to throw any kind of exception (such as NullPointerException
s).
My question is why there is a null check? Was it previously possible in an old version of Java for a constructor to return null? Or is this simply useless and dead code?
No, it has never been possible. Maybe a previous version of the code used some factory method which could return null:
As I discovered today, despite what's said in all the other answers,
Foo x = new Foo(...)
can indeed return null, if said code is running inside a test that uses PowerMock (or some other mocking framework with similar effects):In this case, the code in the constructor(s) of Foo is bypassed altogether for
new Foo(...)
. But if you write a test where you fail to specify the mock in the manner above, you may end up withnull
instead.But even if you are using such a framework, you don't want extra code in your classes, just to gracefully handle the case that you forgot to properly mock the objects in a test! It is not a real-world scenario where your code is intended to run. Code that is only ever active when testing should be eliminated anyway, and in this case it would only ever be active for a broken test.
So even if you're using PowerMock, that second line should rightly be considered "dead code" and removed.
The answer is simple: person who wrote the code was a paranoid c++ programmer. In C++ you may overload operator new and use it as a simple memory allocator (aka malloc).