• Post Reply Bookmark Topic Watch Topic
  • New Topic

Is null check really essential for each and every object  RSS feed

 
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I am right now working on making enhancements for an existing enterprise application which communicates with different systems.
I am seeing a lot of null check in each an every class for each and every object that is being passed.
This really make the code ugly and not easily readable.
Correct me if I am wrong but if you are calling a method from one class to another class from the same module then we dont require null check.
Even being more specific if the object resides in the same JVM then null check is not required(Well if your JVM is full then thats a different story).
Any comments on what I say?

 
Sheriff
Posts: 21136
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, if the result can be null then you should include a null check, or you risk NullPointerExceptions being thrown. You should only skip the null check if a) you're sure the reference cannot be null, or b) you don't care about NullPointerExceptions.
 
Sheriff
Posts: 22846
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that you're asking a design question which has nothing to do with JVMs. You can't reference an object unless it's in the same JVM as your code anyway, so that's a red herring. And your comment about the JVM being "full", whatever that means: I don't understand what that has to do with references being null or not.
 
nithin chinni
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Spoor wrote:Well, if the result can be null then you should include a null check, or you risk NullPointerExceptions being thrown. You should only skip the null check if a) you're sure the reference cannot be null, or b) you don't care about NullPointerExceptions.


So that means if I am having control of my application and I am trying to send a not null object from one class to another class I dont need to right?
And of course I care about null pointer exceptions because i dont want my application to throw null pointer as we are wrapping exceptions with our custom exception class.
 
Marshal
Posts: 56608
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there any way you can prevent nulls remaining in your code?That is prone to NullPointerExceptions (NPE), but allowing nulls into a program is probably the mistake, rather than the NPE itself. In testing, you will know about that early, if you change the constructor to this:That way you can be confident those nulls won’t get into your object in the first place.
 
Rancher
Posts: 4686
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe that the Java original designers were fast and loose with null values. Things like putting null values into lists or sets is just bad. I think the Google Guava folks do a better job. They have made rules, and enforce them.

I use a ton of these in my code, whenever an external user (programmer) could pass in a null argument:

Preconditions.checkNotNull(foo);

You can even give explicit messages using


Preconditions.checkNotNull(foo, "Foo variable is not allowed to be null");

There are a whole suite if similar conditiions checks in the Guava libraries. Open Source, free, well maintained, etc.
http://code.google.com/p/guava-libraries/
 
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nithin chinni wrote:I am seeing a lot of null check in each an every class for each and every object that is being passed.

I guess the question is: what does it do if it is? If all it does is throw an exception, you can write a utility method for it; however, if there is a way to recover, and you can't rely on the provider code not giving you a null object (although it might be worth finding out why not) then, yes, every object must be checked in every situation that it can occur.

BTW, just in case you're interested, my catchall utility is:and then instead of lots of if...throw statements, I just wrap the value in that method call. However, it's just a way to save typing; the check still has to be done.

Winston
 
Rob Spoor
Sheriff
Posts: 21136
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pat Farrell wrote:I believe that the Java original designers were fast and loose with null values. Things like putting null values into lists or sets is just bad. I think the Google Guava folks do a better job. They have made rules, and enforce them.

And what if you actually want to have null values / map keys? I prefer to let the programmer decide; you can use Collections.checkedXXX if you want to prevent null values.

I use a ton of these in my code, whenever an external user (programmer) could pass in a null argument:

Preconditions.checkNotNull(foo);

You can even give explicit messages using


Preconditions.checkNotNull(foo, "Foo variable is not allowed to be null");

Oh I do agree that it's often necessary to have null checks. I use them a lot too, but only where necessary. And you'll probably be happy that Java 7 has new class java.util.Objects with two requireNonNull methods that do the same. They also return the passed value, so you can write code like this:
 
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are plenty of problem spaces where a null value is perfectly legitimate. Maybe I'm a rare bird but pretty much every job I've had has been in such a space. Does our user want our application to crash inexplicably just because they're working with data that wasn't hand-crafted by the developer? Most likely not.
 
Paul Clapham
Sheriff
Posts: 22846
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A lot of people here want to write code so that an IllegalArgumentException will be thrown instead of a NullPointerException. I don't see the benefit of that -- both are unchecked exceptions so they will have the same effect on the calling code.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dennis Deems wrote:There are plenty of problem spaces where a null value is perfectly legitimate. Maybe I'm a rare bird but pretty much every job I've had has been in such a space. Does our user want our application to crash inexplicably just because they're working with data that wasn't hand-crafted by the developer? Most likely not.

No, but there are several cases where people are just lazy; so instead of returning something legitimate (or indeed throwing a more meaningful exception themselves), they just return a null and make it your problem. The classic case of course is failing to return empty collections and arrays.

Winston
 
nithin chinni
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Is there any way you can prevent nulls remaining in your code?That is prone to NullPointerExceptions (NPE), but allowing nulls into a program is probably the mistake, rather than the NPE itself. In testing, you will know about that early, if you change the constructor to this:That way you can be confident those nulls won’t get into your object in the first place.


The problem is I am handling the objects when the method is passed not when the object of that class is created.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul Clapham wrote:A lot of people here want to write code so that an IllegalArgumentException will be thrown instead of a NullPointerException. I don't see the benefit of that -- both are unchecked exceptions so they will have the same effect on the calling code.

I have to disagree there. If the check is for a null parameter in a method, it should most definitely throw an IllegalArgumentException; elsewhere, arguably an IllegalStateException. The only time I expect to see an NPE from my code is when I've made a mistake.

Winston
 
nithin chinni
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But finally I got the whole point, if the scope of the application is in our hands rather than those calls going to another remote module then it should be fine.
But still the code looks ugly because of lot of if statements. May be I will do something using reflection that when ever few things happen it will make a call for null check.
I am not sure but is that a good idea???
 
Pat Farrell
Rancher
Posts: 4686
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nithin chinni wrote:But finally I got the whole point, if the scope of the application is in our hands rather than those calls going to another remote module then it should be fine.
But still the code looks ugly because of lot of if statements.


The point of writing code is to have it reused. When its reused, then its out of your hands.

I think the Guava Preconditions.checkNotNull() is better looking than the string of IF statements.

I think doing this with reflection is a terrible idea.
 
Pat Farrell
Rancher
Posts: 4686
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston Gutkowski wrote:I have to disagree there. If the check is for a null parameter in a method, it should most definitely throw an IllegalArgumentException; elsewhere, arguably an IllegalStateException. The only time I expect to see an NPE from my code is when I've made a mistake.


You are, of course, entitled to your own opinion. But you are in the minority. Most of the Java code that is in wide-spread use, from Java itself, the Apache and Google libraries, throw a NPE when the argument is null.

I most strenuously object to your throwing a IllegalStateException, its not about the state of the object, its about the state of the arguments to the method.
 
Rob Spoor
Sheriff
Posts: 21136
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There was a suggestion to add support for automatic null checks in Java 7, using question marks. For instance:
If object would be null then s would be null. This hasn't made it into Java 7. Perhaps it will be added to Java 8, but I'm not sure.
 
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pat Farrell wrote:
Winston Gutkowski wrote:I have to disagree there. If the check is for a null parameter in a method, it should most definitely throw an IllegalArgumentException; elsewhere, arguably an IllegalStateException. The only time I expect to see an NPE from my code is when I've made a mistake.


You are, of course, entitled to your own opinion. But you are in the minority. Most of the Java code that is in wide-spread use, from Java itself, the Apache and Google libraries, throw a NPE when the argument is null.

Yeah, Sun's description of when to use these two exceptions was rather ambiguous - either NPE or IAE could be appropriate. But most all examples from Sun, and most major libraries since then, have indeed stuck with the NPE approach. Apache Commons' Validate.notNull() used to throw an IAE, but nowadays it throws an NPE instead. And most importantly, Objects.notNull() from Java 7 throws an NPE, not an IAE. That seems to be the easiest way to handle this in the future.

Pat Farrell wrote:I most strenuously object to your throwing a IllegalStateException, its not about the state of the object, its about the state of the arguments to the method.

++
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Spoor wrote:There was a suggestion to add support for automatic null checks in Java 7, using question marks. For instance:
If object would be null then s would be null. This hasn't made it into Java 7. Perhaps it will be added to Java 8, but I'm not sure.

I believe it was "?." rather than ".?". To me it suggested regex syntax - the ? modifier suggests the preceding expression is optional. I'm sorry it didn't make it into Java 7, and I don't think there are any plans for it in Java 8. Too bad.
 
Rob Spoor
Sheriff
Posts: 21136
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I already though the .? looked odd; ?. looks much better. And it's indeed a shame if this will never be introduced into the Java language.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pat Farrell wrote:I most strenuously object to your throwing a IllegalStateException, its not about the state of the object, its about the state of the arguments to the method.

Ah well, we'll have to agree to disagree. In the case that OP was referring to - that of a method handing back a value that may be null (which presumably is why the check is there in the first place) - if the null value is something I can't recover from, then I'd call that putting my program in an "illegal state".

To me, an NPE happens because someone (sometimes me) didn't do their job properly, and therefore a check should attempt to supply some context. Leaving NPEs to occur "naturally" is even worse in my view, because then the exception can occur may places removed from the actual problem, making it more difficult to track down. I'm an old believer of the adage "fail fast, and fail loud".

Winston
 
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can agree that there are good reasons to use either IllegalArgumentException or NullPointerException; personally I use NullPointerException because it's widely established.

However, you should never use IllegalStateException like that. You're supposed to throw IllegalStateException when you're calling a method on an object, at a time you're not supposed to call it; meaning, the object is currently in a state where it's illegal to call the method.

Examples are calling a read method on a stream that's been closed. The current state of the stream does not allow you to read from it.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan van Hulst wrote:However, you should never use IllegalStateException like that. You're supposed to throw IllegalStateException when you're calling a method on an object, at a time you're not supposed to call it; meaning, the object is currently in a state where it's illegal to call the method.

Yeah, reading the docs you're right, so I guess I'd create an InvalidNullException then (thinking about it; maybe as a subtype of NPE), because as far as I'm concerned that's what it is (especially in the case of a returned value). The reason I object to raw NPEs is that they're already thrown by the JRE automatically, so to me they don't add any value to a stacktrace unless backed by a contextual message. So, something's null: What? Why? In what situation? If you're writing a null check utility, why not a contextual null exception?

Winston
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For me the what and why are pretty much always answered by the line number. I don't really need any more context. NPEs are very simple. Something is null, and it shouldn't be. That's why I like them more than IAEs. IAEs could mean all sorts of stuff went wrong. There's nothing ambiguous about an NPE.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan van Hulst wrote:For me the what and why are pretty much always answered by the line number. I don't really need any more context. NPEs are very simple. Something is null, and it shouldn't be. That's why I like them more than IAEs. IAEs could mean all sorts of stuff went wrong. There's nothing ambiguous about an NPE.

Seems I'm rowing against the tide, but all I can say is that your experience of NPEs must be very different from mine. In my view, they're the most pernicious (and often the hardest to find) of errors, because they are a discovery, not an actuation, error; and many programmers simply "let them happen" rather than trying to be proactive about them.

IAE (and as, I've now discovered, thanks to you, ISE) is unambiguous: a parameter passed to a method is wrong. Now the why might be a little tougher to find, but just the presence of an IAE tells me that the programmer was sticking to the "fail fast" principle and trying to give me some added information.

But I won't be using ISE in future .

Winston
 
Paul Clapham
Sheriff
Posts: 22846
43
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Me, I don't particularly care what exception is thrown (as I mentioned earlier). But your point that it should be thrown right away, deliberately, rather than letting it be thrown accidentally later, is a good one. For one thing it's rather misleading when you see a NPE thrown (for example) by the File class when the cause was you passing null to a constructor for an XML parser or something like that. The other disadvantage of letting it be thrown accidentally is that the method's work might be half completed when the exception occurs. This can be a real nuisance if the half-completed work doesn't get rolled back.
 
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On similar lines
Why Null checks are present when they are seemingly not required
https://github.com/MrMEEE/bumblebee/commit/a047be

Hence, people never trust other programmers
 
nithin chinni
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a code snippet and I would like some comments related to the above discussion.
 
Rob Spoor
Sheriff
Posts: 21136
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
teamsList and its elements are guaranteed to be non-null so you can skip those null checks.

Furthermore, you can omit the if (!listItemStr.equals("")) check since if(listItemStr.startsWith("-")) then !listItemStr.equals("").
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If something can legitimately be null--that is, null is a meaningful value, not just a sign that somebody forgot to introduce something--and you need to handle it differently when it is null, then, yes, you have no choice but to insert a null check.

On the other hand, if something is not supposed to be null, and it's documented that it's not allowed to be null, then if it is null, it's the fault of the programmer that let it get that far, and we should most definitely throw an unchecked exception. I'm in the camp that will throw IAE if I explicitly check a method's arg and find it to be null when it's not allowed. Regardless of which specific exception you throw though, it should be thrown reasonably early. If you take that view to its extreme, then, yeah, you end up with annoying null checks at every bloody step of the way, which is cluttersome and not particularly helpful.

So I try to find a middle ground. I don't usually check for nulls in private or package-private methods. And even in public methods, I usually only do if I expect that an erroneous null won't otherwise produce an exception until a much later and harder to find and harder to recover place. This is one of those areas where coding is more art than science. I'm not always consistent in this, but to me it comes down to a best effort to balance readable, uncluttered code with the need to highlight errors sooner rather than later.
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, this code is a good argument for using a smaller indent size. Like say 4 spaces per indent. Or even 2. Not 7. Or 6. Or whatever you're trying to do.

Rob Spoor wrote:teamsList and its elements are guaranteed to be non-null so you can skip those null checks.

Furthermore, you can omit the if (!listItemStr.equals("")) check since if(listItemStr.startsWith("-")) then !listItemStr.equals("").


The "if(listItemStr.length() > 1){" can be omitted as well. We already know the string has at least one character, a '-' at the front. So it will survive the substring(1), and the trim(). If the string had noting after the '-', it will now fail the test against equals(""), so the test for length() > 1 was redundant.

If we had actually needed all those if statements, they could have been ANDed together (with &&) rather than adding another if clause (and indent) for each one.
 
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are, of course, entitled to your own opinion. But you are in the minority. Most of the Java code that is in wide-spread use, from Java itself, the Apache and Google libraries, throw a NPE when the argument is null.


Well I must be in the minority as well. IllegalArgumentException is a lot more tidy and clear than NPEs, something a good programmer will always look to avoid being raised.
 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In my view, they're the most pernicious (and often the hardest to find) of errors, because they are a discovery, not an actuation, error; and many programmers simply "let them happen" rather than trying to be proactive about them.


Winston, I couldn't agree with you more.
 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
IAEs could mean all sorts of stuff went wrong.


If a programmer uses them correctly, this shouldn't be the case. From the exception message, the caller should know the parameter than caused the problem, its erroneous value and which values are acceptable.
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


And no, it's not uncommon for methods to expect arguments that are anything but null. Think of enums.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan van Hulst wrote:

And no, it's not uncommon for methods to expect arguments that are anything but null. Think of enums.


I still prefer to let NPE happen as a result of trying to use null where it cannot be used, and throw IAE when I'm explicitly complaining about an argument. That's what IAE is for. The fact that there exists NPE which could also be interpreted in this case as "illegal null argument" doesn't make it a more natural fit. IMHO, of course.
 
Rob Spoor
Sheriff
Posts: 21136
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This discussion keeps coming up, and like the eternal VI vs Emacs or Eclipse vs Netbeans discussion there will never be a clear winner. So let's stop it right here and now, OK?
 
dennis deems
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Spoor wrote:This discussion keeps coming up, and like the eternal VI vs Emacs or Eclipse vs Netbeans discussion there will never be a clear winner. So let's stop it right here and now, OK?

Clearly there are people still interested in discussing it, and they are writing posts that I, for one, am interested in reading. The fact that YOU are not interested in reading them does not mean the discussion should end. No one is twisting your arm and forcing you to follow this thread, are they?
 
Rob Spoor
Sheriff
Posts: 21136
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You apparently missed the fact that I'm bartender in this forum. That means that I do have to follow this thread. And I don't mind this discussion at all (FYI: I advocate NullPointerException for null arguments), but do we need it dozens of times over and over?
 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob

I agree with you to some degree about things getting repeated but like the previous poster stated, it is interesting to get a consensus of opinion on such topics.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!