The Power of Func<>

Written By John Sonmez

I remember why I love C#.

After spending the last two years or so writing mainly Java code, getting back into Visual Studio felt a little awkward and painful.

Where did all my keyboard shortcuts go?  Why can’t I navigate to members in a class?  Oh, yes Resharper… ah that’s better.

But then it happened.

I was minding my own business writing some code… la la la

public bool IsYummy()
{
if(!areOverridesLoaded)
{
LoadOverrides(); // loads the override from the database into this.theOverride
}
if(this.theOverride != null)
{
return theOverride.IsYummy.GetValueOrDefault(food.IsYummy);
}
return food.IsYummy;
}
public bool IsFruit()
{
if(!areOverridesLoaded)
{
LoadOverrides();
}
if(this.theOverride != null)
{
return theOverride.IsFruit.GetValueOrDefault(food.IsFruit);
}
return food.IsFruit;
}
public bool IsVegetable()
{
if(!areOverridesLoaded)
{
LoadOverrides();
}
if(this.theOverride != null)
{
return theOverride.IsVegetable.GetValueOrDefault(food.IsVegetable);
}
return food.IsVegetable;
}

Oh my, repeated code!  What ever shall I do?

Hmm… It varies by property names only.

Surely I can refactor out the override loading code.  Can’t put it in the constructor, because the goal is to lazy load the overrides from the database.

Func<> to the rescue!

This is the power of Func.  Of delegates really.  You can’t do this in Java folks… Hold on to your chair.  Here we go…. Whee…..

private bool ReturnValueOrDefault(Func<Food, bool?> FoodProperty, bool defaultValue)
{
if (!areOverridesLoaded)
{
LoadOverrides();
}
if (this.theOverride != null)
{
return foodProperty(this.theOverride).GetValueOrDefault(defaultValue);
}
return defaultValue;
}
public bool IsYummy()
{
ReturnValueOrDefault(o => o.IsYummy, food.IsYummy);
}
public bool IsFruit()
{
ReturnValueOrDefault(o => o.IsFruit, food.IsFruit);
}
public bool IsVegetable()
{
ReturnValueOrDefault(o => o.IsVegetable, food.IsVegetable);
}

Good has won…

Evil has been defeated…

Code has been deleted

Thank you Func<>

Don’t forget the Super Combo!

Also, check out the new page I created, a compilation of useful posts I have written about building software in an Agile way.