The "size" of a menu item relates more to a purchase rather than the menu item itself, so it makes sense to do the price calculation outside of the actual menu item. In fact you could just use each IMenuItem
as a place to store the supported sizes (along with the prices) and calculate it in your business layer, or if you had an ItemPurchase
that has two properties: Item
(of type IMenuItem
) and Size
(of type ItemSize
), then that calculation could just live inside there.
Pizza pizza = new Pizza(new Dictionary<ItemSize, decimal>() {
{ ItemSize.Small, 10 },
{ ItemSize.Medium, 20 },
{ ItemSize.Large, 30 },
});
PrintPrice(pizza, ItemSize.Medium);
decimal? GetItemPrice(IMenuItem item, ItemSize size) {
if (!item.Prices.ContainsKey(size)) {
return null;
}
return item.Prices[size];
}
void PrintPrice(IMenuItem item, ItemSize size) {
decimal? price = GetItemPrice(item, size);
if (price is null) {
Console.WriteLine($"Can't buy this item in a {size}");
return;
}
Console.WriteLine($"That'll cost {price}");
}
enum ItemSize {
Small, Medium, Large
}
interface IMenuItem {
IReadOnlyDictionary<ItemSize, decimal> Prices { get; }
}
class Pizza : IMenuItem {
public Pizza(IReadOnlyDictionary<ItemSize, decimal> prices) {
Prices = prices;
}
public IReadOnlyDictionary<ItemSize, decimal> Prices { get; }
}