Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a way to remove duplication in this code

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?

like image 730
leora Avatar asked Apr 25 '10 16:04

leora


2 Answers

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;
}
like image 187
SLaks Avatar answered Sep 21 '22 05:09

SLaks


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).

like image 20
Darin Dimitrov Avatar answered Sep 19 '22 05:09

Darin Dimitrov