473,394 Members | 2,071 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Multiple levels of Null Checking

I find myself doing things like this all the time:

if (
SomeObject != null &&
SomeObject.AnotherObject != null &&
SomeObject.AnotherObject.YetAnother != null &&
SomeObject.AnotherObject.YetAnother.HelpMePlease != null)
{
// Do Something
}

Surely there must be a better way that I am missing? I thought about the
using statement, but that of course depends upon the IDisposable interface
being implemented, right?

Thanks!
Nov 14 '06 #1
13 2475
Karch <no****@absotutely.comwrote:
I find myself doing things like this all the time:

if (
SomeObject != null &&
SomeObject.AnotherObject != null &&
SomeObject.AnotherObject.YetAnother != null &&
SomeObject.AnotherObject.YetAnother.HelpMePlease != null)
{
// Do Something
}

Surely there must be a better way that I am missing? I thought about the
using statement, but that of course depends upon the IDisposable interface
being implemented, right?
That suggests that each of those properties can legitimately be null -
is that always the case? I usually find that most of my properties
should always be non-null, in which case I'm happy for a
NullReferenceException to be thrown if I try to dereference it and it's
null.

Code like the above happens occasionally, but not *that* often. As
another point, I rarely end up using properties 4 levels deep - I
usually try to design classes so that I can ask one class to do what
I'm interested in, without going through several levels.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 14 '06 #2
Rad
On Tue, 14 Nov 2006 13:19:07 -0600, "Karch" <no****@absotutely.com>
wrote:
>I find myself doing things like this all the time:

if (
SomeObject != null &&
SomeObject.AnotherObject != null &&
SomeObject.AnotherObject.YetAnother != null &&
SomeObject.AnotherObject.YetAnother.HelpMePleas e != null)
{
// Do Something
}

Surely there must be a better way that I am missing? I thought about the
using statement, but that of course depends upon the IDisposable interface
being implemented, right?

Thanks!
Not sure if I understand you .. if AnotherObject is a property of
SomeObject, and SomeObject is null, I believe AnotherObject should
also be null
Nov 14 '06 #3
Rad wrote:
On Tue, 14 Nov 2006 13:19:07 -0600, "Karch" <no****@absotutely.com>
wrote:
>I find myself doing things like this all the time:

if (
SomeObject != null &&
SomeObject.AnotherObject != null &&
SomeObject.AnotherObject.YetAnother != null &&
SomeObject.AnotherObject.YetAnother.HelpMePleas e != null)
{
// Do Something
}

Surely there must be a better way that I am missing? I thought about the
using statement, but that of course depends upon the IDisposable
interface being implemented, right?

Thanks!

Not sure if I understand you .. if AnotherObject is a property of
SomeObject, and SomeObject is null, I believe AnotherObject should
also be null
Yes, but SomeObject could be not null yet SomeObject.AnotherObject is null.
That is the order that he is checking.
--
Tom Porterfield

Nov 14 '06 #4
Rad <no****@nospam.comwrote:
On Tue, 14 Nov 2006 13:19:07 -0600, "Karch" <no****@absotutely.com>
wrote:
I find myself doing things like this all the time:

if (
SomeObject != null &&
SomeObject.AnotherObject != null &&
SomeObject.AnotherObject.YetAnother != null &&
SomeObject.AnotherObject.YetAnother.HelpMePlease != null)
{
// Do Something
}

Surely there must be a better way that I am missing? I thought about the
using statement, but that of course depends upon the IDisposable interface
being implemented, right?

Not sure if I understand you .. if AnotherObject is a property of
SomeObject, and SomeObject is null, I believe AnotherObject should
also be null
If SomeObject is null, then trying to evaluate SomeObject.AnotherObject
will throw a NullReferenceException, which is what the OP is presumably
trying to avoid.

Shameless plug - you could do it in Groovy:
if (SomeObject?.AnotherObject?.YetAnother?.HelpMePlea se != null)
{
....
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 14 '06 #5
Jon Skeet [C# MVP] wrote:
>
Shameless plug - you could do it in Groovy:
if (SomeObject?.AnotherObject?.YetAnother?.HelpMePlea se != null)
{
....
}
groooooovy.
--
Tom Porterfield
Nov 14 '06 #6
Yes, they could legitimately be null - I am talking about classes here. One
good example is ADO.NET where you have multiple levels of checking that
needs to happen. Of course, in the below example, I am trying to use the
last level (HelpMePlease instance), but I need to make sure that all those
levels above it are non-null first, otherwise I get the null exception.

Perhaps I expect that some of these could be null a significant number of
times during execution. It seems to be a sort of hack to just wrap the whole
thing in a try-catch and then continue on. After all, I would like to
reserve exceptions for those cases when something unexpected occured and I
can take remedial actions.

"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP************************@msnews.microsoft.c om...
Karch <no****@absotutely.comwrote:
>I find myself doing things like this all the time:

if (
SomeObject != null &&
SomeObject.AnotherObject != null &&
SomeObject.AnotherObject.YetAnother != null &&
SomeObject.AnotherObject.YetAnother.HelpMePleas e != null)
{
// Do Something
}

Surely there must be a better way that I am missing? I thought about the
using statement, but that of course depends upon the IDisposable
interface
being implemented, right?

That suggests that each of those properties can legitimately be null -
is that always the case? I usually find that most of my properties
should always be non-null, in which case I'm happy for a
NullReferenceException to be thrown if I try to dereference it and it's
null.

Code like the above happens occasionally, but not *that* often. As
another point, I rarely end up using properties 4 levels deep - I
usually try to design classes so that I can ask one class to do what
I'm interested in, without going through several levels.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Nov 14 '06 #7
Rad
On Tue, 14 Nov 2006 14:47:42 -0500, "Tom Porterfield"
<tp******@mvps.orgwrote:
>>
Not sure if I understand you .. if AnotherObject is a property of
SomeObject, and SomeObject is null, I believe AnotherObject should
also be null

Yes, but SomeObject could be not null yet SomeObject.AnotherObject is null.
That is the order that he is checking.
My mistake ... I seem to have read he was checking FOR null.

Whoops
Nov 14 '06 #8
Karch <no****@absotutely.comwrote:
Yes, they could legitimately be null - I am talking about classes here.
Just because they're classes doesn't mean they can legitimately be
null. I often have classes where the properties are guaranteed not to
be null - if anything is null it indicates there's an error in my code.
(Not all properties work that way, but many do.)

A good example of this might be
StreamWriter.Encoding.BodyName.Length - if any of the properties in
that path ended up being null, I'd be very concerned, despite them all
being classes (until the final property returning an int).
One good example is ADO.NET where you have multiple levels of checking that
needs to happen.
Well, in some cases - but not in others. ADO.NET is a very broad
example :)
Of course, in the below example, I am trying to use the
last level (HelpMePlease instance), but I need to make sure that all those
levels above it are non-null first, otherwise I get the null exception.

Perhaps I expect that some of these could be null a significant number of
times during execution. It seems to be a sort of hack to just wrap the whole
thing in a try-catch and then continue on. After all, I would like to
reserve exceptions for those cases when something unexpected occured and I
can take remedial actions.
Oh you certainly shouldn't do that, no :)

If you often need to do this for a particular "tree" of properties, you
could put it into a static helper method in the top-level class, but
basically you need all the tests you've got, if every property can
legitimately be null.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 14 '06 #9
Karch,

This may be an architectural red flag. Sometimes, I find myself
writing:

if (SomeObject != null && SomeObject.AnotherObject != null)
DoSomething();

but I've rarely gone past two levels. Having 4-level-deep objects is a
sign that either you're working on an incredibly complex system, or
you've mis-designed your object model. I've built some incredibly
complex systems and they still don't go past two levels.

Incidentally, typed DataSets as created by the VS.NET tools make you
dig pretty deep and run into issues like this sometimes. I personally
believe this is an architectural problem, and that object references to
deep structured data, as opposed to things like XPath/XQuery, is
generally difficult. Prime evidence of this is the renaming that you
need to do to make sure nothing collides in your typed DataSet.
Microsoft seems to agree, because they're fixing this in .NET 3.0 with
LINQ.

That having been said, one possible solution is validation. I'm
assuming SomeObject.AnotherObject is a property, not that AnotherObject
is a public member. If it's a public member, it probably shouldn't be.
By making it a property, you can assure that it's not null on the way
in, so you don't have to check it later.

Another way around is a solid contract check:

if (SomeObject == null)
return "Sorry, invalid";

// Now we know SomeObject is not null.
if (SomeObject.AnotherObject == null)
return "Sorry, invalid."

// etc.

It's more code, but it's easier to read and maintain. You can comment
each line, and you can do better value-add checks (e.g. -- SomeObject
== null || SomeObject.Length 5). If you're unit testing (you're unit
testing, right? I hope you are if it's an incredibly complex system),
this is the easiest way to make sure your code passes now and will pass
later.

Otherwise, it's not bad to implement IDisposable. If your objects are
using resources -- they probably should be otherwise you've likely made
your object model too deep -- it's the best way to free them up without
burdening the user with Close()-ing your objects. Learn the pattern for
IDisposable and C#-style destructors and you'll be building more robust
code anyway.

HTH.

Stephan

Karch wrote:
I find myself doing things like this all the time:

if (
SomeObject != null &&
SomeObject.AnotherObject != null &&
SomeObject.AnotherObject.YetAnother != null &&
SomeObject.AnotherObject.YetAnother.HelpMePlease != null)
{
// Do Something
}

Surely there must be a better way that I am missing? I thought about the
using statement, but that of course depends upon the IDisposable interface
being implemented, right?

Thanks!
Nov 14 '06 #10
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP************************@msnews.microsoft.c om...
>SomeObject != null &&
SomeObject.AnotherObject != null &&
SomeObject.AnotherObject.YetAnother != null &&
SomeObject.AnotherObject.YetAnother.HelpMePleas e != null)
As
another point, I rarely end up using properties 4 levels deep - I
usually try to design classes so that I can ask one class to do what
I'm interested in, without going through several levels.
Thus adhering to the "Law" of Demeter, which I generally try to do, as well.

///ark
Nov 14 '06 #11
I'm thinking you could implement the concept of "null objects". The
net effect of it is that code using the object doesn't do null
checking; it doesn't have to.

In other words you instantiate an object but it's property or method
has "do nothing" behavior. It returns whatever value is appropriate
for "empty" or "nothing returned" or "none" or simply do nothing, or
whatever. Thus you never actually get "null" and the client code
doesn't have to explicty do a null check/trap.

The null object idea is actually a design pattern. You define an
abstract class then have both the "real" object and the "null" object
inherit from it. Thus your client code never knows (or cares) when it's
getting a null object.

On 2006-11-14 13:19:07 -0600, "Karch" <no****@absotutely.comsaid:
I find myself doing things like this all the time:

if (
SomeObject != null &&
SomeObject.AnotherObject != null &&
SomeObject.AnotherObject.YetAnother != null &&
SomeObject.AnotherObject.YetAnother.HelpMePlease != null)
{
// Do Something
}

Surely there must be a better way that I am missing? I thought about
the using statement, but that of course depends upon the IDisposable
interface being implemented, right?

Thanks!

Nov 14 '06 #12
Bob,

Clever. The use of structs (which are not nullable) is a converse but
similar implementation.
Stephan
Bob Jones wrote:
I'm thinking you could implement the concept of "null objects". The
net effect of it is that code using the object doesn't do null
checking; it doesn't have to.

In other words you instantiate an object but it's property or method
has "do nothing" behavior. It returns whatever value is appropriate
for "empty" or "nothing returned" or "none" or simply do nothing, or
whatever. Thus you never actually get "null" and the client code
doesn't have to explicty do a null check/trap.

The null object idea is actually a design pattern. You define an
abstract class then have both the "real" object and the "null" object
inherit from it. Thus your client code never knows (or cares) when it's
getting a null object.

On 2006-11-14 13:19:07 -0600, "Karch" <no****@absotutely.comsaid:
I find myself doing things like this all the time:

if (
SomeObject != null &&
SomeObject.AnotherObject != null &&
SomeObject.AnotherObject.YetAnother != null &&
SomeObject.AnotherObject.YetAnother.HelpMePlease != null)
{
// Do Something
}

Surely there must be a better way that I am missing? I thought about
the using statement, but that of course depends upon the IDisposable
interface being implemented, right?

Thanks!
Nov 15 '06 #13
"Karch" <no****@absotutely.comwrote in message
news:%2****************@TK2MSFTNGP03.phx.gbl...
>I find myself doing things like this all the time:

if (
SomeObject != null &&
SomeObject.AnotherObject != null &&
SomeObject.AnotherObject.YetAnother != null &&
SomeObject.AnotherObject.YetAnother.HelpMePlease != null)
{
// Do Something
}

Surely there must be a better way that I am missing? I thought about the
using statement, but that of course depends upon the IDisposable interface
being implemented, right?
This is probably no different to any other code you need to repeat over and
over. If it gets used many times, put it in a function.

Michael
Nov 15 '06 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: RJ | last post by:
We currently send product releases to our customers, and often have to include scripts that need to be ran on the Oracle databases (also do it for SqlServer customers, but we use a different set of...
3
by: DarthMacgyver | last post by:
Hello, I recently wrote a survey application. Each question is very similar. The first questions gives me a problem when there are multiple people taking the survey (The Database connection...
6
by: Stephen Cook | last post by:
Having worked through the problems around enabling the document function using an XmlUrlResolver I started work on building a useful class to hide the intricacies. Trying to generalise the process...
9
by: WL | last post by:
Hey, all. I'm creating an array of strings (char **argv style) on the fly, and using realloc to create string pointers, and malloc for the strings itself (if that makes any sense). I'm using the...
2
by: James X. Li | last post by:
Is there a way to implement multiple login forms for ASP.NET applications? With our application we want to implement simple login form for normal resources (downloadable files), but more rigorous...
47
by: Mark | last post by:
why doesn't .NET support multiple inheritance? I think it's so silly! Cheers, Mark
16
by: Paul Schwann | last post by:
Hi group, I am relatively new to C# (although I have a lot of programming excperience in other languages like Java and C). Currently I am searching for a solution to this problem: Suppose you...
4
Uncle Dickie
by: Uncle Dickie | last post by:
Sorry for the slightly obscure Title. I couldn't really think of a way to describe my scenario accurately, but here goes: The following bit of code retrieves the latest bill of materials for a...
8
bilibytes
by: bilibytes | last post by:
Hi everyone, I'm facing a database design problem. I want to make a sort of networking solution for the clients of my site in which they would be able to share or keep private some of their...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.