I have this Food class with 20 properties. I need to use this Food class and output 3 different files, using variations of these 20 fields. For example, File 1 contains output only 8 fields. File 2 contains 15 fields. File 3 contains 18 fields.
So right now, I have these 3 separate methods.
FoodService()
{
void WriteRecommendedFood(IList<Food> foodList);
void WriteRecommendedFoodCalculation(IList<Food> foodList);
void WriteRecommendedFoodAllEligibleFoods(IList<Food> foodList);
}
So I'd write:
public void WriteRecommendedFood(IList<Food> foodList)
{
using (StreamWriter sw = new StreamWriter("file.csv", false)
{
StringBuilder sb = new StringBuilder();
foreach (Food f in foodList)
{
sb.Append(f.Field1);
//Repeat for the # of fields I want to spit out
sb.Clear();
sw.WriteLIne(sb.ToString());
}
sw.Close();
}
}
I feel like I'm writing the same code three times (with slight variations). I started to read up on different design patterns like Visitor and Strategy pattern, but I'm not sure which design pattern to improve my code. (Note: I only need to output it to a comma delimited file at this time. Also, from the UI side, the user gets to select which one they want to output (either one to all 3 files.) Any suggestions?