This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
The moose likes Java in General and the fly likes is it wise to return a null from a method ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "is it wise to return a null from a method ?" Watch "is it wise to return a null from a method ?" New topic
Author

is it wise to return a null from a method ?

Ajay Xavier
Ranch Hand

Joined: Jan 03, 2005
Posts: 109
hi,

consider the following code


is it a good practice to return null from a method when some condition is not met?

Regards,
Ajay.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
We had a lengthy and rather deep discussion about this point and language theory the other day. There wasn't a real practical answer out of the whole thing.

The problem is your method signature promises to return a TestObj. Returning null doesn't really meet the promise and feels like you're trying to return some flag along with the actual data. The flag is not part of the signature. It complicates the logic of any code that calls the method and opens the risk of null pointer exceptions any time some new client trusts the signature to tell the whole story. That all sounds pretty negative and should give you good reason to try not to return null.

There's a neat choice called Null Object Pattern where you return a custom class that does whatever "no object" should do. For example, we had an trainer once who said to do this:

This was bad for all the reasons given above. After the class our team used this:

Can you guess what a custom NullTransaction does in those methods? Nothing at all.

Does that help or confuse?


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

is it a good practice to return null from a method when some condition is not met?

No, quite the contrary. Never return null, never accept null. For all cases of using null, there is always a more suitable alternative. This also means that you must abandon Object.equals (tied to every declared type) and therefore collections - since this method declares to accept null without failure.


Tony Morris
Java Q&A (FAQ, Trivia)
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
In addition to what Stan said, when "condition not satisfied" actually is a sign for a programming error, I prefer to throw some kind of RuntimeException.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
James Sabre
Ranch Hand

Joined: Sep 07, 2004
Posts: 781

There are times when it is accptable to return NULL. For example, the get() method in the java.util.Map interface returns NULL if the map contains no mapping for a given key. Sun could have considered this to be an error and thrown an Error but they chose to return NULL.

In my view there is no hard and fast rule to cover this. I try not to return NULL and I only throw an Exception (or Error) from a method if the user breaks the contract defined for the method.

When the returned object is an array I never return NULL. In my view it is alway better to return an empty array.


Retired horse trader.
 Note: double-underline links may be advertisements automatically added by this site and are probably not endorsed by me.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by James Sabre:
There are times when it is accptable to return NULL. For example, the get() method in the java.util.Map interface returns NULL if the map contains no mapping for a given key. Sun could have considered this to be an error and thrown an Error but they chose to return NULL.

Sun also chose to accept null in the Map.put method. Certainly the associative type that I use never accepts null and it is a provably better solution (given an axiom and all that...).
pascal betz
Ranch Hand

Joined: Jun 19, 2001
Posts: 547
Tony: What would "your" Map then return if you lookup a key that does not exist ? I guess you would need to do it with a "contains" check first ?


instead of:



i agree with you that returning "null" should be avoided but i think that sometimes it is useful/necessary.

concerning "never accept null" why this ?
what speaks against this ?


pascal
Matt Harrah
Ranch Hand

Joined: Aug 05, 2006
Posts: 54
I'm sorry, but I have to disagree with the folks who are claiming that you should never return null from a method, if that is indeed what they are claiming. There are certainly appropriate times to return null references from a method. I would agree that you should not return a null if an exceptional condition occurs, because there are exceptions for that.

If, for example, you are doing a database lookup for "that object which has this value in this column" and no object matches, returning a null is appropriate, intuitive, and in line with the principle of least surprise. Good design in my opinion.

If, however, you are doing some method and a precondition of the method is not met, it would be better to throw an exception (IllegalArgumentException?) than to return null.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Matthew Harrah:

If, for example, you are doing a database lookup for "that object which has this value in this column" and no object matches, returning a null is appropriate, intuitive, and in line with the principle of least surprise. Good design in my opinion.


Matt Harrah
Ranch Hand

Joined: Aug 05, 2006
Posts: 54
Originally posted by Ilja Preuss:


Ok, I see what you're doing, and I don't dispute that this would work, but why is this categorically better than returning a null? A reasonable person could argue this is overengineered; a case of cool > useful. The code supplied certainly doesn't convince me that returning a null is never appropriate - it only convinces me that there is another way to do it, which I never disputed.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
cool > useful

Well, that's always in the eye of the beholder. Google for Tablizer and see someone who thinks the whole OO thing is cool > useful. I draw the line at a different place than Tony does, and you may draw it somewhere else.

It's a valid argument that the contract "public Thing getThing()" says nothing about returning nulls, and it's not really possible to express the "if none found return null" in the signature. How much does that little fib in the signature and the required comments and test for null bother you? Maybe a lot, maybe not at all.

I find studying Tony's arguments well worth while, and maybe he's dragging my line in the sand a little his way now & then.
[ August 05, 2006: Message edited by: Stan James ]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Matt Harrah:
Ok, I see what you're doing, and I don't dispute that this would work, but why is this categorically better than returning a null? A reasonable person could argue this is overengineered; a case of cool > useful.


A reasonable person could also argue that that style actually has some advantages over returning null.

For example, you don't need to document what returning null actually means. The API itself makes quite clear what is happening.

Consequently, you can't overlook that the method might return null. That is, it's quite unlikely that you forget to handle the "no object found" case.

This style is quite popular in the circles where OO got "invented" (the Smalltalk community, for example), and some of the "gurus" I trust swear on it. I haven't yet tried it very much, but I won't reject it before I've put some more effort into giving it a chance. I'm sure I will learn something.
Naseem Khan
Ranch Hand

Joined: Apr 25, 2005
Posts: 809
I found this article very good in the context of the above discussion.

The Null Flag bug pattern

Naseem


Asking Smart Questions FAQ - How To Put Your Code In Code Tags
Matt Harrah
Ranch Hand

Joined: Aug 05, 2006
Posts: 54
Originally posted by Ilja Preuss:


A reasonable person could also argue that that style actually has some advantages over returning null.

For example, you don't need to document what returning null actually means. The API itself makes quite clear what is happening.

That's true to a point. One certainly must document what a return value of null means -- hopefully it's in line with "least surprise" as discussed earlier, and would be what you would expect a null value to mean, like nothing matched the value in a lookup method -- and this is the situation I'm claiming it's ok to return a null in. If it's not, I agree with you that returning something other than a null or using some other mechanism is warranted to indicate the strange situation.

But I somewhat disagree that you do not need to document the alternative method. It is true that the API itself makes it quite clear what is happening, as you say, but in my opinion that does not excuse developers from documenting what is happening. I think it is also true that

is also extremely clear what's going on as well.


Consequently, you can't overlook that the method might return null. That is, it's quite unlikely that you forget to handle the "no object found" case.
That's the best argument you've made.

This style is quite popular in the circles where OO got "invented" (the Smalltalk community, for example), and some of the "gurus" I trust swear on it. I haven't yet tried it very much, but I won't reject it before I've put some more effort into giving it a chance. I'm sure I will learn something.


Oh, I don't reject this alternative way of doing it at all. I think it's a pretty cool approach. What I reject is broad dogmatic statements like "it's NEVER ok to return a null". There's a difference between saying "There's a better way than returning null and here it is" and "It's NEVER ok to return a null".

As far as the gurus are concerned, some of the gurus I trust like Josh Bloch (no stranger to SmallTalk) have written loads of code (such as the Collections API) that return null from their methods and I don't see many people complaining. But like I said, your approach is a pretty cool one, and you're right, does have some advantages over returning null -- simplicity unfortunately is not one of them (by comparison), but sometimes simplicity is not everything.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by pascal betz:
Tony: What would "your" Map then return if you lookup a key that does not exist ? I guess you would need to do it with a "contains" check first ?

No, avoid exceptions. I gave a big long rant on this forum recently about how to use a "quasi-closure" and the example I used was (if I remember rightly):

This solution has costs associated and they are almost certainly not immediately obvious - certainly I've met nobody yet who can see it all - and it requires pointing out. I'd find the rant but I seem to be incompetent at using the search facility of this forum (hesitant to blame the tool).
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

Oh, I don't reject this alternative way of doing it at all. I think it's a pretty cool approach. What I reject is broad dogmatic statements like "it's NEVER ok to return a null". There's a difference between saying "There's a better way than returning null and here it is" and "It's NEVER ok to return a null".

Is this a broad dogmatic statement: "never stab yourself in the eye"? Yes it is - it requires an axiom in order to become legitimate. It is an axiom that many people assume, but let's explicitly state it anyway: "one does not wish to inflict pain unto oneself". Under this axiom, the statement is directly contradictory to the stated objective.

Given this, I offer you a challenge. Find any formal definition of "software" then try to legitimise "returning null" under the context.

As far as the gurus are concerned, some of the gurus I trust like Josh Bloch (no stranger to SmallTalk) have written loads of code (such as the Collections API) that return null from their methods and I don't see many people complaining. But like I said, your approach is a pretty cool one, and you're right, does have some advantages over returning null -- simplicity unfortunately is not one of them (by comparison), but sometimes simplicity is not everything.

Bloch is not a guru and collections are poorly written. I'll find you hundreds of people who complain about any method that documents to return null - it's just a matter of selection (I assume you don't "hang" with this audience). I wish these demigods would not be put up on a pedestal - it is misleading those who truly wish to explore knowledge - not any fault of those who occupy the pedestal of course.
Matt Harrah
Ranch Hand

Joined: Aug 05, 2006
Posts: 54
If you are of the opinion that Bloch is a hack, Tony, I suppose we will have to agree to disagree on this matter.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
I can't say much about Bloch, but I'm not at all impressed by the OO skills of the Sun developers in general.

Kent Beck is currently writing a book about implementation patterns in Java - something like the Java version of "Smalltalk Best Practice Patterns". *That* sounds promising...
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24166
    
  30

Originally posted by Tony Morris:
Given this, I offer you a challenge. Find any formal definition of "software" then try to legitimise "returning null" under the context.


OK. I will use Alton Brown's definition of "software" as "the food ingredients that are used in a recipe."

Now, legitimize "returning null?" I unscrew the lid of the nutmeg jar, and insert a teaspoon. I withdraw the teaspoon, and it's empty. "Huh," I say, visually checking for a null return. "I'd better use some allspice instead." And I toss the nutmeg into the recycle bin, grab the allspice, and finish the recipe.

My point being that "returning null" is the most natural thing in the world, and it's absolutely unclear to me how anyone could make a blanket statement about its universal goodness or evil.

Another thing I'd like to point out: your use of a "pseudoclosure" seems to me quite analagous to the null object pattern, excepting that the responsibility for "handling null" moves from the target (in the null object pattern) back to the caller. Forcing the caller to handle null... where have I heard of that before? Oh yes: exceptions. Forcing the caller to provide a null-handler-object is absolutely equivalent to forcing the caller to provide a null-handler-catch-block; only the syntax is different.

I'm certainly not arguing in favor of Sun's library designs being pinnacles of the form. But I am arguing that there are no absolutes; many things you want to banish do in fact have their place, and most of all that functional programming is merely one star in the galaxy of ways to express software designs; and it's not a superior or privileged one, either.


[Jess in Action][AskingGoodQuestions]
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by Matt Harrah:
If you are of the opinion that Bloch is a hack, Tony, I suppose we will have to agree to disagree on this matter.


Sure. The last I heard from him was after I listened to one of his talks then I subsequently emailed him and Neal Gafter about how it was incorrect. Neal was of the opinion at the time that null was unavoidable and provided what I believe was (unexpectedly) quite flawed reasoning.

Neal also accused me of copying his work at the time to which I responded with a proof that my work was original due to the dates (mine existed in 2002 and his existed in mid-2005) and I haven't heard from him since I provided him with my RCS logs demonstrating the facts.

In any case, and since Ernest has made the comment that "passing a callback" and null are semantically equivalent (which is incorrect), I will provide a brief introduction to a critical analysis of null (something that I desperately hope Bloch and Gafter have done by now ).

'null' exists in an OO language to handle the case of an 'invalid order of operation invocation'. Given the following contract:

... there are many orders of invocation, but one of them is an invalid use case. Simply, calling "observeEffect" before "causeEffect" is invalid. You can create a more realistic case:

There are many potential solutions to this. You can cause a signal to the client that they have invoked an invalid operation (i.e. throw an exception). This means that the client is exposed to a superset of their requirement and should the client use some of what is exposed but is not in the set of requirements, the client will observe a runtime failure. Certainly not very nice to expose it in the first place and perhaps even quite rude

Another alternative is to expose only the observing operation after the causing operation is invoked:

That's fine, but now you have functional programming in disguise. There is no higher-order communication (the single benefit of OO as it digresses from software) since you cannot talk about a "person".

Other solutions are semantic equivalents to Haskell's Maybe (which is subtly different from Java's dynamically-typed null). I hope it's clear now that passing a callback is not semantically equivalent to returning a dynamically-typed placeholder for "nothing".
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
'null' exists in an OO language to handle the case of an 'invalid order of operation invocation'.


That's interesting. Null is often used to indicate things that are not invalid, but merely optional. We get this from database folks, I guess. We'd need an object with some behavior to distinguish from "not entered by the user" and "a zero length string" without resorting to flags?
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Ernest Friedman-Hill:

My point being that "returning null" is the most natural thing in the world


I don't see anything natural about it. It's certainly something most of us are more than used to. But that doesn't make it a good idea.

From another perspective: not so long ago, using goto statements was the most natural thing in the world.

it's absolutely unclear to me how anyone could make a blanket statement about its universal goodness or evil.


I'm also not very fond of blanket statements.

On the other hand, when I hear someone report that he tries to avoid using null at all, and that he finds that good things come out of it - my first reaction is that I find it interesting and thought provoking. And when I hear it a second or third time from different people, I start to wonder whether I should try that for a while, too.

After all, who am I too say that it is *not* universally evil? Perhaps the feeling I'm so used to is in fact pain...
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

After all, who am I too say that it is *not* universally evil? Perhaps the feeling I'm so used to is in fact pain...

The reason you might be thinking this is because the udnerlying logic is flawed but somewhat common. I had a conversation with a colleague yesterday who also shares an interest in logic and methods of reasoning.

Simply, there is no such thing as a "blanket statement" and there is no such thing as "evil". One requires a premise within which to either legitimise or contradict (aka "evil") the stated objective. This is generally called deductive reasoning.

It is absolutely "evil" for a calculator to expose the ability to multiply two numbers - if the client of the calculator adds apples all day long. This is a "leak of requirement". The Java community generally calls it "evil" or some such which then leads to the "blanket statement" refutations. Both sides are flawed.

What often occurs is someone makes a statement "X is evil" without providing the premise on which the statement was made (perhaps it was misacknowledged?). The premise or axiom is not an axiom after all - since not all participants of the audience assume the same axiom - you can observe the axiom shift around followed by many "yeah buts". The common axiom among this community generally should be some formal definition of "software", which for example, assumes the notion of linear time relative to the observer (aka computational progression). Since many members of the community are not educated on the formalities of either software or logic, many ill-founded debates ensue. A debate should be a learning exercise for one or both parties.

In the end, it is of utmost importance that one thinks for oneself. I think I've ranted on enough times lately.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: is it wise to return a null from a method ?
 
Similar Threads
Servlet condition block moved to Helper class
Inward vs outward negation from performance point of view
How to crate Multiple ArrayList from one ArrayList
How to find a file (any file) in Java
Can a method in a class call itself?