Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A nicer way to handle null references in a object hierarcy

I’m looking for a nice way to handle a null reference in object hierarchy.

ie:

if(null == Object1.Object2.Object3.Property)

This example will throw a Null Reference exception if say Object2 is null.

In my case I don't care what is null, just that something is. I don't really want to put try/catches around each place that I want to do something like this, so I’ve been looking for an alternative.

I've experimented with the ?? operator but this makes for some ugly looking code after two levels.

Any ideas appreciated.

like image 757
squig Avatar asked Dec 23 '22 11:12

squig


1 Answers

Now this might be on a tangent... but I'd suggest a design change to avoid the ugliness and pain

Calling Object1.Object2.Object3.Property violates the law of demeter. Instead if you're supposed to get to that property, Object1 should expose a Property itself... So you should be calling Object1.RetrievedFromTheDepthsProperty
Why this is needed.. is that if the designer of the Type Object2 changes the type of Object returned by the 'Object3' field/property to one that doesn't have the Property you're looking for, you'd be hosed. The client knows too much about the internal structure of Object1. If Object1 encapsulated where the data is located internally, you'd be safe against future changes. Also this property can do all the null checking internally as required... leaving you with the much cleaner

if (Object1.RetrievedFromTheDepthsProperty == null) {...}
like image 164
Gishu Avatar answered Feb 16 '23 20:02

Gishu