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
On Jun 9, 2:22 pm, Lew <(E-Mail Removed)> wrote:
> 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.

I thought that this was obvious.

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

No, my question is: How often a null object reference is NOT an
error?

> 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.
>

Exactly! So why do you have to throw an exception or even check if the
object is a null reference since a NullPointerException will be thrown
anyway? And if a NullPointerException is thrown, your code has a
problem. I believe that this is why NullPointerException is a run-time
exception and not a compile time..
> --
> Lew


 
Reply With Quote
 
 
 
 
Arved Sandstrom
Guest
Posts: n/a
 
      06-09-2008
"pek" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
> 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?

[ SNIP ]

In Lew's example above it's simply the case that method "foo" expects a
non-null argument by contract. A method like that is under no obligation to
do anything other than throw an NPE if it gets a null argument.

What Lew is pointing out is this: the code that calls "foo" actually has two
valid paths of execution - one, "arg" is null, and two, "arg" is not null.
Let's say that the calling code is in method "bar"...this method considers a
null value of arg" to be legitimate, checks for it, and does
"handleNullSituation" with it. "bar" handles the non-null case by calling
"foo" - as we've said, "foo" does *not* consider a null argument to be
valid.

Let's consider another example, that can see null values in several
different ways. Your method "bar" is using method "get" in interface Map.
This returns null if there is no mapping for the key or the key maps to
null. First note - "get" throws an NPE if the map does not permit null keys
(like Hashtable)...this is an example of a method simply not accepting a
null argument at all. So you potentially have 4 possibilities here:

1) "get" throws an NPE;
2) "get" returns a null and you determine that the key exists;
3) "get" returns a null and the key does not exist;
4) "get" returns a non-null.

Case 1 shouldn't happen, but eventually will. You should be aware of whether
your map does or does not accept null keys - it it doesn't, but *your*
method (namely "bar") could *legitimately* get null keys, check for a null
key and do something else. If your calling code (namely "bar") does *not*
expect to ever get a null value to pass to "get", call "get" all the time,
and if "get" (see below, it's actually "containsKey" that barfs) throws an
NPE just let that percolate up from "bar" as well - whatever called "bar"
wasn't doing what it should have been doing.

Cases 2, 3 and 4 are handled by a construct similar to what Lew has:

if (someMap.containsKey(key)) {
Object obj = someMap.get(key);
if (obj == null) {
// key exists but maps to null
handleNullValue();
} else {
// "foo" expects a non-null argument
foo(key);
}
} else {
// handle situation where key is not mapped at all
handleNonmappedKey();
}

Note that in the above snippet, if the map does not accept null keys, the
snippet itself is behaving like method "foo" - it does not expect null keys
and makes no effort to handle them. In this situation (the map does not
accept null keys) it's up to "bar" to look for them *if* "bar" itself
expects null keys. If even "bar" never expects to see null keys, neither
"bar", the above code snippet, nor "foo" make any effort to check for null
keys...just let the NPE percolate up.

And where the map can accept null keys, the above code snippet behaves
reasonably. Note: if it's for some reason important to you (for a map that
can accept null keys) to differentiate between the key being null and the
key just not being in the map, "bar" can deal with that too (either in the
else block or before the code snippet is reached).

I hope this example helped. To me null handling is a simple question of,
where do you expect to see it, both as arguments and return values? In the
above, depending on the situation, "bar" is potentially doing null checks
both on arguments it gets and on return values from methods it calls, and is
also aware of how the methods it calls handle null arguments. And as I've
indicated, you look for and handle null if you expect to see it...if you
don't, let an NPE happen.

AHS


 
Reply With Quote
 
 
 
 
Tom Anderson
Guest
Posts: n/a
 
      06-09-2008
On Mon, 9 Jun 2008, Lew wrote:

> Also, an object cannot be 'null'. A reference can be.


Ahem:

http://c2.com/cgi/wiki?NullObject

Although of course that's really something quite different!

tom

--
Kein Mehrheit Fur Die Mitleid
 
Reply With Quote
 
Tom Anderson
Guest
Posts: n/a
 
      06-09-2008
On Mon, 9 Jun 2008, Lew 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.


This is very silly advice.

> What's the matter, is it too hard to copy-and-paste a try-catch block?


Around *every* *single* *method* (or code block, or whatever granularity
you fancy)? Yes. Yes it is.

> 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.


This is the crux of it - some methods do need hardening against duff
parameters, like nulls, NaNs, out-of-range integers, objects that are
invalid in more subtle ways, etc, but not all. You say all public methods,
but i think that's overkill. Firstly, it only needs to be on exported
methods - methods that you expect outside code to call; the main entry
points to the component or package or whatever. If outside code wants to
call your internal methods with duff arguments, fine, let it handle the
consequences. Secondly, i'm generally quite happy to have code screws up
when given a null, as long as it's clear that i shouldn't pass a null.
That again hands the responsibility for not passing in a null to the
caller.

It would be nice if java could express a requirement for non-nullity in
the type system. Some type systems forbid nulls from normal variables, and
if you want a variable that can be null, you have to call it an
"Option<Foo>" or something. I quite like this idea - most variables
shouldn't be null, so make that the default, but provide a way of having
them be null when that's okay. A simple syntax would be a question mark
after the type - implying it might be one of those, or it might not:

String foo = null ; // compile-time error
String? bar = null ; // that is okay
String baz = bar ; // also a compile-time error - can't assign from ? to not-?
String qux = (String)bar ; // okay, albeit icky

That's probably in Scala or something.

Hey, maybe we could use ! to mean const. HHOK!

tom

--
Kein Mehrheit Fur Die Mitleid
 
Reply With Quote
 
Tom Anderson
Guest
Posts: n/a
 
      06-09-2008
On Mon, 9 Jun 2008, Lew wrote:

> Robert wrote:
>> Burning Angel ? have you lost your mind ?

>
> You might not realize this, but angels put out more BTU than good
> hickory.


The fumes are dreadful, though. Make sure your stovepipe is in good
working order.

tom

--
Kein Mehrheit Fur Die Mitleid
 
Reply With Quote
 
Ulrich Eckhardt
Guest
Posts: n/a
 
      06-09-2008
Lew wrote:
> 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.


I disagree. You should not catch exceptions you can not handle. Maybe it's
not what you meant, but if I read the above I imagine code that calls each
function that could throw in a microscopic try-catch clause, i.e. a code
that is completely cluttered with error handling code. Coding like that
completely obliterates the whole advantage of exceptions in the first
place, then you can go back to just using returncodes like in C.

> 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.


....or live with the fact that the code calling this code will have an
exception thrown at it, just like this code does.

Uli

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

 
Reply With Quote
 
Daniel Pitts
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. 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).

If it is truly an error to pass in null to a method, allow the JVM to
product a null-pointer exception. If you can handle (null) as a special
case, then you should check for null. If you want to be as informative
as possible, check for null, and throw a NullPointerException with a
descriptive message (not just "Null!").
>
> 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){}
> }
> }

Why do you have these in two different try/catch blocks, and why do you
just throw the exception away? You have made try/catch blocks both
worthless AND burdensome, when it can easily be useful and relatively
painless.
>
> 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.


You should put the possible causes of null pointer exceptions in your
JavaDoc. for example.
/**
* Initializes Hell
* @throws a NullPointerException if devil or fire is null.
*/
public Hell(Devil devil, Fire fire) {
if (devil == null || fire == null) {
throw new NullPointerException();
}
}


Note that NullPointerException is an unchecked exception, since it
generally indicates that the programmer has made a mistake.

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


Absolutely not, however, throwing an Exception, rather than an NPE is
overkill, and trying to catch exceptions caused by nulls that could be
avoided is bad practice.

Hope this helps,
Daniel.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
 
Reply With Quote
 
Stefan Ram
Guest
Posts: n/a
 
      06-09-2008
Ulrich Eckhardt <(E-Mail Removed)> writes:
>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.


When a method does not catch checked exceptions it receives
from the operations it invokes, those checked exceptions will
be thrown from this method an therefore they become part of
the interface of this method.

When the implementation of this method will be changed, those
checked exceptions might change, too, because now other
operations will be invoked, so other checked exceptions might
need to be declared, so the interface will need to change, too.

To avoid this, a method might catch checked exceptions and
wrap them in objects of a custom exception type, so that the
interface will not have to change when the implementation
will change.

 
Reply With Quote
 
Daniel Pitts
Guest
Posts: n/a
 
      06-09-2008
Lew wrote:
> bugbear wrote:
>> Lew wrote:
>>>
>>> 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.

>>
>> I would disagree, or at least qualify.
>>
>> > A method must be coded to handle any input that fits
>> > its specification.

>>
>> If a method is not supposed to be passed null, I would
>> regard correct bahaviour as throwing a
>> NullPointerException.
>>
>> Since this will happen as soon as the object
>> is used, I would regard the correct behaviour
>> as almost inevitable in many common case.
>>
>> e.g.
>>
>> a.doSomething()

>
> Sure, if you don't have any logging or exception handling. But that
> possibility should have been prevented in the first place - just letting
> an NPE happen is a bad, bad practice.
>

It depends on where it happens. If a method can't reasonable be
designed to handle null, then it should throw an NPE if it is given a
null. If the calling code can prevent a null from being passed in, than
it should do so, and then no NPE will be generated.

In general, NPE's usually caused by programmer error, not bad input.
Although the practice holds the same. If a precondition is required for
a method to function properly, it must be met by the calling code, or
the method should reasonably throw an exception. If the exception could
have been anticipated and prevented at the client call site, a unchecked
exception should be used, otherwise a suitable checked exception should
be used.



--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
 
Reply With Quote
 
Roedy Green
Guest
Posts: n/a
 
      06-09-2008
On Mon, 9 Jun 2008 02:37:00 -0700 (PDT), pek <(E-Mail Removed)>
wrote, quoted or indirectly quoted someone who said :

>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).


The nice thing about Java is it will check for null and throw an
exception without writing any code.. If all that is you are going to
do, there is not much point in manual checking. If however you can
dodge the null and carry on --where null means there is no such thing,
rather than a coding error, then of course you have to check for it.
--

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
 
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