Im working on a e-commerce sort of application.
Entities are:
Product
withList<Expense> Expenses
Expense
withDescription
props which is referring to packaging, transport, administrative costs etc.
I need to have at least 2 types of expenses:
- Relative expense (amount in percentage, calculated off the product price) and
- Absolute expense (amount in numbers)
What i tried doing is having an
abstract class Expense
with props:Id
,Description
.class RelativeExpense : Expense
withAmountInPercentage
props andclass AbsoluteExpense : Expense
withAmount
props.
For calculating expenses I'm having a GetTotalExpenseAmount(Product p)
method:
public decimal GetTotalExpenseAmount(Product p)
{
decimal totalExpenses = 0;
foreach (var expense in p.Expenses)
{
if(expense.GetType() == typeof(RelativeExpense))
{
totalExpenses += p.BasePrice * (expense as RelativeExpense).AmountInPercentage / 100;
}
else if(expense.GetType() == typeof(AbsoluteExpense))
{
totalExpenses += (expense as AbsoluteExpense).Amount;
}
}
return totalExpenses;
}
My question is, is this a good practice? Reason i'm asking is because AS operator is doing casting and i know that can be expensive performance-wise. Plus i will have a Logger
which will print out all expanses for a single product and therefore this foreach
with as
operator will be used again.
Is there any other way i can achieve what i want, but with better/cleaner code and performance? Maybe different modeling? Any ideas how should i approach this?
I'd suggest a single class with
IsRelative
property:or even