Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Checking for null parameter

Reply
Thread Tools

Checking for null parameter

 
 
pek
Guest
Posts: n/a
 
      06-09-2008
So is checking for null pointer a good practice? I mean, 90% of the
times you have any object as a parameter, you really want that object
to be something other than null. Otherwise you have to blot your code
into an unlimited number of lines of try, catch etc (and sometimes you
will fail doing any correct error handling).

Just to make my question more clear, here is an example:

class Test {
private A a;
public Test(A a) throws Exception {
if ( a == null ) throw new Exception("Null!");
this.a = a
}
}

class Hell {
private Devil d;
private Fire f;
public Hell(Devil d, Fire f) throws Exception {
if ( ( d == null ) || ( f == null ) ) throw new
Exception("Null!");
this.d = d; this.f = f;
}
public void burnAngel(Angel a) {
if ( a == null ) throw new Exception("Null!");
a.burn();
}
}

class Main {
public static void main(String[] args) {
try {
Test t = new Test(new A());
} catch (Exception e) {}
try {
Hell h = new Hell(new Devil(), new Fire());
} catch (Exception e){}
}
}

So, is this all necessary? I mean, if A, Devil, Fire and Angel is null
and I know that they should not be, then that means that I have an
error in my code. There is no reason to explicity tell someone that
the object should not be null. If I do, I have to try catch almost 80%
of my code.

What do you think? If checking for null overkill or not?
 
Reply With Quote
 
 
 
 
ttrifonov
Guest
Posts: n/a
 
      06-09-2008
Hi,

It's very bad idea to throw java.lang.Exception for null parameters.
It's better to throw NullPointerException or IllegalArgumentException.
These exception are run-time exception so you don't need to use any
try-catch blocks. It's good idea to add a comment in javadoc what will
happened with null values and who is responsible to check for them.

Regards,
Tanyu
 
Reply With Quote
 
 
 
 
Ulrich Eckhardt
Guest
Posts: n/a
 
      06-09-2008
pek wrote:
> So is checking for null pointer a good practice? I mean, 90% of the
> times you have any object as a parameter, you really want that object
> to be something other than null.


If a function is documented to accept null, I would know it does. Otherwise,
I would assume it doesn't accept null.

> Otherwise you have to blot your code
> into an unlimited number of lines of try, catch etc (and sometimes you
> will fail doing any correct error handling).


Cluttering code in microscopic try-catch-clauses is IMHO a typical beginners
misconception about how to use exceptions. Maybe it's also (bad) influence
from programming languages like C (or badly taught C++..) that require the
programmer to always check returnvalues.

> class Test {
> private A a;
> public Test(A a) throws Exception {
> if ( a == null ) throw new Exception("Null!");
> this.a = a
> }
> }


Two things:
1. There is a dedicated NullPointerException.
2. Dereferencing ("using") 'a' in above example would throw that exception
if 'a' was 'null'. Depending on the circumstances, you might want to get
that exception early (like when only storing it) or can live with getting
it later (i.e. when finally using it).

> class Hell {
> private Devil d;
> private Fire f;
> public Hell(Devil d, Fire f) throws Exception {
> if ( ( d == null ) || ( f == null ) ) throw new
> Exception("Null!");
> this.d = d; this.f = f;
> }
> public void burnAngel(Angel a) {
> if ( a == null ) throw new Exception("Null!");
> a.burn();
> }
> }

[...]
> try {
> Hell h = new Hell(new Devil(), new Fire());
> } catch (Exception e){}

[...]
> So, is this all necessary? I mean, if A, Devil, Fire and Angel is null
> and I know that they should not be, then that means that I have an
> error in my code. There is no reason to explicity tell someone that
> the object should not be null. If I do, I have to try catch almost 80%
> of my code.
>
> What do you think? If checking for null overkill or not?


Try to make that code more realistic. First you create hell, then burn some
angels. In either case, if fire is null, you end up with an exception in
the catch handler. The only difference is that in one case it is a bit
earlier and in the other a bit later. I'd go for the 'later', because the
additional effort of checking every reference if it is null just clutters
the code.

Uli

--
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

 
Reply With Quote
 
pek
Guest
Posts: n/a
 
      06-09-2008
On Jun 9, 1:26 pm, Lew <(E-Mail Removed)> wrote:
> pek wrote:
> > So, is this all necessary? I mean, if A, Devil, Fire and Angel is null
> > and I know that they should not be, then that means that I have an
> > error in my code. There is no reason to explicity tell someone that
> > the object should not be null. If I do, I have to try catch almost 80%
> > of my code.

>
> > What do you think? If checking for null overkill or not?

>
> A method must be coded to handle any input that can be sent to it. Otherwise
> it will break when it gets the wrong input.
>
> What's the matter, is it too hard to copy-and-paste a try-catch block? If
> that's too much effort, change jobs and be a ditch digger.
>
> The purpose of those try-catch blocks (and other logic to handle anomalous
> input) is to make it possible to fix the program when something bad happens.
>
> Generally, design your algorithms so that undesired inputs are never passed in
> the first place. Your keywords to google are "algorithm invariants" and the
> Java 'assert' keyword. Warning: 'assert' is not for input checking! Its
> purpose is to enforce algorithm invariants.
>
> What you have to check in private methods is different from what you have to
> check in public methods, on account of you completely control calls into
> private methods but not others.
>
> If 'null' is a possible input, and you need to handle it differently from
> other values, then you absolutely, inexorably and inarguably must check for it.
>
> Every time.
>
> Without fail.
>
> --
> Lew


So, since 90% of the times I need a non-null object in my code, I
should throw an exception. So that means that 80% of any code that
calls a method or constructs an object that needs another object
should be inside a try catch.

The problem isn't the time it takes to write the code, I do, after
all, use an IDE that does it automatically. The problem is the
complexity of the error handling. Consider the following code:

public doSomething() throws Exception {
try {
Test t = new Test(this.aString);
...
} catch (Exception e) { }
// I don't care if Test threw an exception
try {
TestAgain a = new TestAgain();
...
// I do care if TestAgain threw an exception, so continue in the
try
// But I want to handle Tester exception differently
Tester ts = null;
try {
ts = new Tester(a);
} catch (Exception e) { throw e }
...
ts.doSomething();
}
}

Assuming that exceptions are thrown only in case of a null object,
that looks ugly.

Besides, Java it self doesn't excplicity say that a method throw an
Exception for null, it throw a run-time NullPointerException whenever
the object is being used. So, the problem is you, because somewhere in
your code you didn't do something correct. Otherwise all methods and
claases in Java would have a signature of "throws Exception" and then
all your code would be in a try catch.

Oh, have in mind that this is more than I theoritical question than an
opinion. I'm not saying that null checking should be avoided.
 
Reply With Quote
 
pek
Guest
Posts: n/a
 
      06-09-2008
On Jun 9, 1:41 pm, ttrifonov <(E-Mail Removed)> wrote:
> Hi,
>
> It's very bad idea to throw java.lang.Exception for null parameters.
> It's better to throw NullPointerException or IllegalArgumentException.
> These exception are run-time exception so you don't need to use any
> try-catch blocks. It's good idea to add a comment in javadoc what will
> happened with null values and who is responsible to check for them.
>
> Regards,
> Tanyu


That where exactly my thoughts. And since NullPointerException is
thrown "automatically" when trying to use a null object, you don't
even have to throw it. Just stating in the Javadoc that the objects
should not be null should be enough.

I mean, I consider handling object when they are null a special case,
not standard! I always want my objects not to be null!
 
Reply With Quote
 
pek
Guest
Posts: n/a
 
      06-09-2008
On Jun 9, 1:51 pm, Lew <(E-Mail Removed)> wrote:
> ttrifonov wrote:
> > Hi,

>
> > It's very bad idea to throw java.lang.Exception for null parameters.
> > It's better to throw NullPointerException or IllegalArgumentException.
> > These exception are run-time exception so you don't need to use any
> > try-catch blocks.

>
> If an exception is thrown, runtime or not, it's a pretty darn good idea that
> the calling code have a catch block for it, if one doesn't take the care to
> pass only valid values in the first place.
>
> Given a method 'foo()' that can throw an IllegalArgumentException, the best
> practice is to pass only valid values to it in the first place:
>
> if ( arg == null )
> {
> handleNullSituation();
> }
> else
> {
> foo( arg );
> }
>
> NOW you don't need a try-catch, but if you don't do the pre-check, then you
> absolutely would need to catch the exception.
>
> --
> Lew


So, what do you consider a better way of coding? Doing a pre-check,
thus avoiding all your methods to have an exception handling a null
state, or having try catch everywhere?

Let me rephrase my question: How often does a method or constructor
that accepts an object in it's parameter list CAN WORK if the object
is null?
 
Reply With Quote
 
pek
Guest
Posts: n/a
 
      06-09-2008
On Jun 9, 1:51 pm, Ulrich Eckhardt <(E-Mail Removed)> wrote:
> pek wrote:
> > So is checking for null pointer a good practice? I mean, 90% of the
> > times you have any object as a parameter, you really want that object
> > to be something other than null.

>
> If a function is documented to accept null, I would know it does. Otherwise,
> I would assume it doesn't accept null.
>
> > Otherwise you have to blot your code
> > into an unlimited number of lines of try, catch etc (and sometimes you
> > will fail doing any correct error handling).

>
> Cluttering code in microscopic try-catch-clauses is IMHO a typical beginners
> misconception about how to use exceptions. Maybe it's also (bad) influence
> from programming languages like C (or badly taught C++..) that require the
> programmer to always check returnvalues.
>
> > class Test {
> > private A a;
> > public Test(A a) throws Exception {
> > if ( a == null ) throw new Exception("Null!");
> > this.a = a
> > }
> > }

>
> Two things:
> 1. There is a dedicated NullPointerException.
> 2. Dereferencing ("using") 'a' in above example would throw that exception
> if 'a' was 'null'. Depending on the circumstances, you might want to get
> that exception early (like when only storing it) or can live with getting
> it later (i.e. when finally using it).
>
>

That exactly my point. Trying to figure out when do you have to check
for an object that is null brings complexity in your code. If you
decide that you will throw an exception when you will actually use it,
you have to think "Is it too late? Maybe I should have thrown it when
I was storing it.". Isn't it obvious that a would have SOME use
eventually? Otherwise it wouldn't be in the constructor in the first
place. If the method could work even when a is null, wouldn't it be
more convinient to state it in the javadoc?
>
>
>
> > class Hell {
> > private Devil d;
> > private Fire f;
> > public Hell(Devil d, Fire f) throws Exception {
> > if ( ( d == null ) || ( f == null ) ) throw new
> > Exception("Null!");
> > this.d = d; this.f = f;
> > }
> > public void burnAngel(Angel a) {
> > if ( a == null ) throw new Exception("Null!");
> > a.burn();
> > }
> > }

> [...]
> > try {
> > Hell h = new Hell(new Devil(), new Fire());
> > } catch (Exception e){}

> [...]
> > So, is this all necessary? I mean, if A, Devil, Fire and Angel is null
> > and I know that they should not be, then that means that I have an
> > error in my code. There is no reason to explicity tell someone that
> > the object should not be null. If I do, I have to try catch almost 80%
> > of my code.

>
> > What do you think? If checking for null overkill or not?

>
> Try to make that code more realistic. First you create hell, then burn some
> angels. In either case, if fire is null, you end up with an exception in
> the catch handler. The only difference is that in one case it is a bit
> earlier and in the other a bit later. I'd go for the 'later', because the
> additional effort of checking every reference if it is null just clutters
> the code.
>

Hahahahahhahahah! I didn't think of creating a realistic example. The
word Hell just pop in my head and I named all the other a little
relevant. But I loved the way you looked at it
> Uli
>
> --
> Sator Laser GmbH
> Geschftsfhrer: Thorsten Fcking, Amtsgericht Hamburg HR B62 932


 
Reply With Quote
 
Robert
Guest
Posts: n/a
 
      06-09-2008
pek a crit :
> So is checking for null pointer a good practice? I mean, 90% of the
> times you have any object as a parameter, you really want that object
> to be something other than null. Otherwise you have to blot your code
> into an unlimited number of lines of try, catch etc (and sometimes you
> will fail doing any correct error handling).
>
> Just to make my question more clear, here is an example:
>
> class Test {
> private A a;
> public Test(A a) throws Exception {
> if ( a == null ) throw new Exception("Null!");
> this.a = a
> }
> }
>
> class Hell {
> private Devil d;
> private Fire f;
> public Hell(Devil d, Fire f) throws Exception {
> if ( ( d == null ) || ( f == null ) ) throw new
> Exception("Null!");
> this.d = d; this.f = f;
> }
> public void burnAngel(Angel a) {
> if ( a == null ) throw new Exception("Null!");
> a.burn();
> }
> }
>
> class Main {
> public static void main(String[] args) {
> try {
> Test t = new Test(new A());
> } catch (Exception e) {}
> try {
> Hell h = new Hell(new Devil(), new Fire());
> } catch (Exception e){}
> }
> }
>
> So, is this all necessary? I mean, if A, Devil, Fire and Angel is null
> and I know that they should not be, then that means that I have an
> error in my code. There is no reason to explicity tell someone that
> the object should not be null. If I do, I have to try catch almost 80%
> of my code.
>
> What do you think? If checking for null overkill or not?


Burning Angel ? have you lost your mind ?
 
Reply With Quote
 
Robert
Guest
Posts: n/a
 
      06-09-2008
Lew a écrit :
> pek wrote:
>> So, what do you consider a better way of coding? Doing a pre-check,
>> thus avoiding all your methods to have an exception handling a null
>> state, or having try catch everywhere?

>
> Prevention is better than curing.
>
>> Let me rephrase my question: How often does a method or constructor
>> that accepts an object in it's parameter list CAN WORK if the object
>> is null?

>
> Your question is syntactically incomplete, and I am not sure what you
> are asking.
>
> Also, an object cannot be 'null'. A reference can be.


You seems a little bit picky.

>
> If you're asking for statistics on how many classes have constructors
> that accept 'null' parameters, it's a meaningless and pointless


kind of harsh. I guess pek was thinking about statistics on nullness

> question. In the first place, *every* non-private constructor that
> takes a reference parameter must work if the argument is null. Failure
> to deal with a possible input is a flaw in the code - programmer error.


Lew said
 
Reply With Quote
 
Jack
Guest
Posts: n/a
 
      06-09-2008
Lew a écrit :
> Ulrich Eckhardt wrote:
>> Try to make that code more realistic. First you create hell, then burn
>> some
>> angels. In either case, if fire is null, you end up with an exception in
>> the catch handler. The only difference is that in one case it is a bit
>> earlier and in the other a bit later. I'd go for the 'later', because the
>> additional effort of checking every reference if it is null just clutters
>> the code.

>
> Best practice is to prevent errors. Failing that, catch them early.
>
> "Just clutters the code" is not a valid criticism. If it is necessary
> to check for an exception, clutter or not, it must be done.
>
> The reason to check early is to facilitate correction of problems. The
> later a bug is caught and logged, the harder it is to discern the true
> cause.
>
> There are ways to make code easier to read and maintain, but the
> sacrifice of good engineering principles is not among them.
>
> To get "uncluttered" code, structure your algorithms so that non-nullity
> of a variable is an 'assert'able invariant. NPEs will become
> impossible, obviating the need for corresponding catch blocks. Then you
> get your lack of "clutter" as a concomitant to good engineering, not a
> violation thereof.


Yet some invariant tools sometimes throw NPE (ESCJava2 in my memory).
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
checking for a null value in a data reader ]-[aTc]-[ ASP .Net 6 11-28-2011 02:53 PM
"stringObj == null" vs "stringObj.equals(null)", for null check?? qazmlp1209@rediffmail.com Java 5 03-29-2006 10:37 PM
problems with checking against NULL value in mssql2000 db excelleinc.com ASP .Net 1 09-10-2004 09:51 PM
checking the null values in the database column............ Jimmy Crider ASP .Net 3 02-18-2004 01:51 PM
Checking For Null DB Fields Troy ASP .Net 2 08-21-2003 08:49 PM



Advertisments