NullsafeGet extension method? Simplicity for the cost of readability??

When programming, there is often the the situation where you have to continuously do the null-check in order to not get exceptions. For instance take the dummy example of a Person object with an according Address object. Like this...
class Person
{
public string Name { get; set; }
public Address Address { get; set; }
}

class Address
{
public string Street { get; set; }

public string GetCountry()
{
return "Italy"; //just dummy code
}
}
Now consider the case where you'd like to access the Street property of the Address object
//some code, person is an instance of Person
textBoxStreet.Text = person.Address.Street;
I guess everyone agrees that this will give a nice NullReferenceException if the Address object is null. This results in continuously (now this is just a dummy example) checking for null
...
if(person.Address != null)
textBoxStreet.Text = person.Address.Street;
In this example it even looks simple enough, but in certain conditions it may be quite awkward. I actually found the approach on a Stackoverflow post which pointed to this blog here. A solution is to use extension methods which - apparently - can also be applied to a null instance of an object.
public static class NullSafeGetExtension
{

public static U NullsafeGet<T, U>(this T t, Func<T, U> fn)
{
if (t != null)
return fn(t);
else
return default(U);
}

}
I called it "NullsafeGet", another commonly used name is "IfNotNull"...it's just a matter of preferences. This solution allows to write the above code like
//some code, person is an instance of Person
textBoxStreet.Text = person.NullsafeGet(x => x.Address).NullsafeGet(x => x.Street);
This turns out to be a quite nice solution since you don't need all of the nested ifs. In this example it was obviously simple enough to write the if instead of using the extension methods. This piece from the Stackoverflow post probably illustrates the advantage in a more clear way:
string activeControlName = null;
var activeForm = Form.ActiveForm;
if (activeForm != null)
{
var activeControl = activeForm.ActiveControl;
if(activeControl != null)
{
activeControlname = activeControl.Name;
}
}
And with the extension method solution...
activeControlname = activeForm.NullsafeGet(x => x.ActiveControl).NullsafeGet(x => x.Name);
Although this looks quite nicely, my doubt is on the readability of the code itself....So I don't know whether I'll really use it...
What do you think??
Kindle

Comments

0

Your ad here?