I can't find a good performant and legibility way to write some computed inside a class. Imagine the following class and all ways to get the FinalPrice:
public class Order {
public Order(Product[] products) {
Items = products;
option 1: Having a variable declaration for each property that want to be computed, horrible legibility
var orderPrice = products.Sum(p => p.Price * p.Quantity);
var orderTaxes = products.Sum(p => p.Taxes * p.Quantity);
var orderDiscount = products.Sum(p => p.Price * p.Quantity * p.Discount);
OrderPrice = orderPrice;
OrderTaxes = orderTaxes;
OrderDiscount = orderDiscount;
FinalPrice = orderPrice + orderTaxes - orderDiscount;
option 2: having the problem of the order in the class matters! FinalPrice line can't be before the others or it won't work but won't throw error.
OrderPrice = products.Sum(p => p.Price * p.Quantity);
OrderTaxes = products.Sum(p => p.Taxes * p.Quantity);
OrderDiscount = products.Sum(p=> p.Price * p.Quantity * p.Discount);
FinalPrice = OrderPrice + OrderTaxes - OrderDiscount;
option 3: rewriting all the formulas - Bad for manteinance. Most likely to instroduce differences in prices later on.
FinalPrice = products.Sum(p => p.Price * p.Quantity) +
products.Sum(p => p.Taxes * p.Quantity) -
products.Sum(p => p.Price * p.Quantity * p.Discount);
}
option 4: using getters. This will be calculated everytime it's called. This is a simple calculation, but assume something more code heavily.
public decimal FinalPrice { get {
return OrderPrice + OrderTaxes - OrderDiscount;
} }
}
option 5: using a function. Is this a good or bad thing ??
public decimal CalculateFinalPrice() {
return OrderPrice + OrderTaxes - OrderDiscount;
}