//Let's create a an overloaded alternative method for the updated version public static Drink OrderDrink(DrinkMenu option) { Drink drink = new Drink(); if (option.type == AvailableDrinks.Expresso) { drink = new Expresso(); } else if (option.type == AvailableDrinks.Tea) { drink = new Tea(); } else if (option.type == AvailableDrinks.IceTea) { drink = new IceTea(); } try { drink.Prepare(); //Remove type as it is not used drink.HasMilk = option.hasMilk; drink.HasSugar = option.hasSugar; drink.HasChocolate = option.hasChocolate; return(drink); } catch (Exception ex) { Console.WriteLine("We are unable to prepare your drink: " + ex.ToString()); System.IO.File.WriteAllText(@"c:\Error.txt", ex.ToString()); } //Let's return nothing if something fails return(null); }
//If we want to make it even more DRY and easier to mantain, we could use dynamic T types with a base class filter, so it allows only derivated classes and avoid runtime errors //and get rid off the factory pattern. We would need to remove AvailiableDrinks from the DrinkMenu. This would require to refactor code using this library public static T OrderDrinkDynamic <T>(DrinkMenu option) where T : Drink, new() { try { T drink = new T(); drink.Prepare(); //Remove type as it is not used drink.HasMilk = option.hasMilk; drink.HasSugar = option.hasSugar; drink.HasChocolate = option.hasChocolate; return(drink); } catch (Exception ex) { Console.WriteLine("We are unable to prepare your drink: " + ex.ToString()); System.IO.File.WriteAllText(@"c:\Error.txt", ex.ToString()); } //Let's return nothing if something fails return(null); }