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!