M
marlow.andrew
I am mainly a C++ programmer currently moving more and more into java.
So when I look at java code I tend to do so with a C++ hat on.So
please bear that in mind as you consider this question: Is it normal
for (java) methods to check an object reference for null before using
it?
In C++ the equivalent idea is checking an input pointer for null
before using it. For C++ it is normal to do this and throw an
application-specific exception if the pointer is null. The check is to
do with ensuring class invariants and is particularly useful in the
constructor. In C++ it is disastrous not to do the check, since the
entire executable explodes into tiny fragments when you reference
through a null pointer. Of course, java is more forgiving and throws a
NPE. I guess this is why java code tends not to make the check. If a
class invariant is violated this indicates a coding error and under
those conditions you do want a full diagnostic trace to tell you where
the invariant is violated. The C++ solution gives this to you but only
if you are a diligent coder. In java you don't have to write any code
but you don't quite get the full solution. You only get told where the
code blew up, not where the class invariant was first violated.
Regards,
Andrew Marlow
So when I look at java code I tend to do so with a C++ hat on.So
please bear that in mind as you consider this question: Is it normal
for (java) methods to check an object reference for null before using
it?
In C++ the equivalent idea is checking an input pointer for null
before using it. For C++ it is normal to do this and throw an
application-specific exception if the pointer is null. The check is to
do with ensuring class invariants and is particularly useful in the
constructor. In C++ it is disastrous not to do the check, since the
entire executable explodes into tiny fragments when you reference
through a null pointer. Of course, java is more forgiving and throws a
NPE. I guess this is why java code tends not to make the check. If a
class invariant is violated this indicates a coding error and under
those conditions you do want a full diagnostic trace to tell you where
the invariant is violated. The C++ solution gives this to you but only
if you are a diligent coder. In java you don't have to write any code
but you don't quite get the full solution. You only get told where the
code blew up, not where the class invariant was first violated.
Regards,
Andrew Marlow