c'è un modo per eliminare la duplicazione in questo codice
-
01-10-2019 - |
Domanda
Ho un metodo che assomiglia a questo:
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;
}
e ho un altro metodo che assomiglia a questo:
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;
}
C'è un modo per consolidare questo come l'unica cosa diversa è i nomi di proprietà?
Soluzione
Fare un metodo GetServing
separata:
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;
}
Altri suggerimenti
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;
}
che potrebbe essere utilizzato in questo modo:
var x = Get(value => value.X);
var y = Get(value => value.Y);
Nota:. SomeType
è il tipo di Servings[0]
che se ho ben capito il codice correttamente dovrebbe essere lo stesso come il tipo di parser.Parse(Description)
Supponendo parser.Parse()
restituisce la stessa classe che detiene Servings[]
, è possibile creare un nulla oggetto di quel tipo, per cui entrambi X e Y sono uguali a zero. Allora si potrebbe avere una funzione che restituisce il primo elemento di Servings[]
, se esiste, o new FoodDescriptionParser.Parser(Description)
, se Description
esiste, o, infine, che oggetto nullo. E raccogliere la X o Y a seconda delle necessità.