473,729 Members | 2,150 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Multiple levels of Null Checking

I find myself doing things like this all the time:

if (
SomeObject != null &&
SomeObject.Anot herObject != null &&
SomeObject.Anot herObject.YetAn other != null &&
SomeObject.Anot herObject.YetAn other.HelpMePle ase != 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 2498
Karch <no****@absotut ely.comwrote:
I find myself doing things like this all the time:

if (
SomeObject != null &&
SomeObject.Anot herObject != null &&
SomeObject.Anot herObject.YetAn other != null &&
SomeObject.Anot herObject.YetAn other.HelpMePle ase != 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
NullReferenceEx ception 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.co m>
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****@absotut ely.com>
wrote:
>I find myself doing things like this all the time:

if (
SomeObject != null &&
SomeObject.Ano therObject != null &&
SomeObject.Ano therObject.YetA nother != null &&
SomeObject.Ano therObject.YetA nother.HelpMePl ease != 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****@absotut ely.com>
wrote:
>I find myself doing things like this all the time:

if (
SomeObject != null &&
SomeObject.Ano therObject != null &&
SomeObject.Ano therObject.YetA nother != null &&
SomeObject.Ano therObject.YetA nother.HelpMePl ease != 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.Anot herObject 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****@absotut ely.com>
wrote:
I find myself doing things like this all the time:

if (
SomeObject != null &&
SomeObject.Anot herObject != null &&
SomeObject.Anot herObject.YetAn other != null &&
SomeObject.Anot herObject.YetAn other.HelpMePle ase != 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.Anot herObject
will throw a NullReferenceEx ception, which is what the OP is presumably
trying to avoid.

Shameless plug - you could do it in Groovy:
if (SomeObject?.An otherObject?.Ye tAnother?.HelpM ePlease != null)
{
....
}

--
Jon Skeet - <sk***@pobox.co m>
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?.An otherObject?.Ye tAnother?.HelpM ePlease != 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.co mwrote in message
news:MP******** *************** *@msnews.micros oft.com...
Karch <no****@absotut ely.comwrote:
>I find myself doing things like this all the time:

if (
SomeObject != null &&
SomeObject.Ano therObject != null &&
SomeObject.Ano therObject.YetA nother != null &&
SomeObject.Ano therObject.YetA nother.HelpMePl ease != 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
NullReferenceEx ception 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.co m>
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.Anot herObject 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****@absotut ely.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.En coding.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.co m>
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.Anot herObject != 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.Anot herObject 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.Ano therObject == 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.Leng th 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.Anot herObject != null &&
SomeObject.Anot herObject.YetAn other != null &&
SomeObject.Anot herObject.YetAn other.HelpMePle ase != 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

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

Similar topics

2
12745
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 scripts for that). Some of the Sql scripts can be quite long, and so we break them out to their own script files and call them all from one main ..sql file, using sqlplus to execute it all. The admin would run the file like:
3
6111
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 Timed out) I am using the Data Access Application Blocks as ASP.NET (using VB.NET) and SQL 2000. In there first question there can be up to 27 answers. So I figured instead of making 27 different trips to the database I woulc just concatenate my...
6
2486
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 I've hit a snag. How do I resolve multiple external references? The transform method on a stylesheet only takes one resolver, not an array Stephen
9
4029
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 construct ptr = realloc(ptr, size); *ptr = malloc(string_length); strncpy(ptr, src, string_length); to call realloc() multiple times. This should be ok, right?
2
4662
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 login forms for tasks like administration and configuration. The current ASP.NET seems only to allow to a single login form via the authentication element in web.config in the root directory. One work-around for our problem is implementing a...
47
3638
by: Mark | last post by:
why doesn't .NET support multiple inheritance? I think it's so silly! Cheers, Mark
16
8392
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 have 3 methods A, B and C. All of them shall be run threaded (I/O tasks) and one after another. I can create a thread and schedule one method just like:
4
1858
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 part: SELECT b.BOMPartID, b.ComponentPartID, b.Quantity, b.ScrapPercent FROM BillOfMaterials b JOIN Versions v ON v.VersionID = b.VersionID WHERE v.StatusID = 1 AND b.PrimeComponent = 1
8
2153
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 contact information. so if i have a table like this: CREATE TABLE `users_retailers_account_info` ( `id` bigint(15) unsigned NOT NULL auto_increment, `email` varchar(255) NOT NULL default 'N/A',
0
8761
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9426
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9280
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9200
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9142
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6016
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2162
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.