views:

109

answers:

3

i have a method that looks like this:

   private double GetX()
    {
        if (Servings.Count > 0)
        {
            return Servings[0].X;
        }
        if (!string.IsNullOrEmpty(Description))
        {
            FoodDescriptionParser parser = new FoodDescriptionParser();
            return parser.Parse(Description).X;
        }
        return 0;
    }

and i have another method that looks like this:

  private double GetY()
    {
        if (Servings.Count > 0)
        {
            return Servings[0].Y;
        }
        if (!string.IsNullOrEmpty(Description))
        {
            FoodDescriptionParser parser = new FoodDescriptionParser();
            return parser.Parse(Description).Y;
        }
        return 0;
    }

Is there any way to consolidate this as the only thing different is the property names?

+10  A: 
private double Get(Func<SomeType, double> valueProvider)
{
    if (Servings.Count > 0)
    {
        return valueProvider(Servings[0]);
    }
    if (!string.IsNullOrEmpty(Description))
    {
        FoodDescriptionParser parser = new FoodDescriptionParser();
        return valueProvider(parser.Parse(Description));
    }
    return 0;
}

Which could be used like this:

var x = Get(value => value.X);
var y = Get(value => value.Y);

Remark: SomeType is the type of Servings[0] which if I understand your code correctly should be the same as the type of parser.Parse(Description).

Darin Dimitrov
Clever and clean, but I have a felling this is using a big hammer on a very small nail.
dbkk
+12  A: 

Make a separate GetServing method:

private Serving GetServing() {
    if (Servings.Count > 0)
        return Servings[0];

    if (!string.IsNullOrEmpty(Description)) {
        FoodDescriptionParser parser = new FoodDescriptionParser();
        return parser.Parse(Description);
    }
    return null;
}

private double GetX() {
    Serving serving = GetServing();
    if (serving == null) return 0;
    return serving.X;
}

private double GetY() {
    Serving serving = GetServing();
    if (serving == null) return 0;
    return serving.Y;
}
SLaks
You can cut a line with `return (serving == null) ? 0 : serving.X`
dbkk
+1. I like this a bit better than Dimitrov's lambda approach, because your way is more focused on the meaning, rather than the mechanics of the program.
Joren
+1 For code clarity, and not just smartness.
Nayan
A: 

Assuming parser.Parse() returns the same class that Servings[] holds, you could create a null object of that type, for which both X & Y are zero. Then you could have a function that returns the first element of Servings[], if it exists, or new FoodDescriptionParser.Parser(Description), if Description exists, or, finally, that null object. And gather the X or Y as needed.

Carl Manaster