which is better ???
public class Order
{
private double _price;
private double _quantity;
public double TotalCash
{
get
{
return _price * _quantity;
}
}
or
public class Order
{
private double _totalCash;
private double _price;
private double _quantity;
private void CalcCashTotal()
{
_totalCash = _price * _quantity
}
public double Price
{
set
{
_price = value;
CalcCashTotal();
}
}
public double Quantity
{
set
{
_price = value;
CalcCashTotal();
}
}
public double TotalCash
{
get
{
return _totalCash;
}
}
There are tradeoffs. If the calculations simple and does not take a long time, then put it in the get. It makes your life easier, because you don't have to worry about doing the check in every set that total price is dependant on, which could lead to mistakes.
If the calculation takes a lot of time, then you could also take a hybrid approach. You could set a IsDirtyTotalPrice boolean in all the dependant sets, and then do the calculation on the fly in the get and cache it so that the get only calculates the variable when it needs to. You don't do the calculation in the sets because there could be a lot of them, and you wan to do the calculation as few times as possible.
public class Order
{
private double _totalCash;
private double _price;
private double _quantity;
private _IsDirtyTotalCash = true;
private void CalcCashTotal()
{
_totalCash = _price * _quantity
}
public double Price
{
set
{
_price = value;
_IsDirtyTotalCash = true;
}
}
public double Quantity
{
set
{
_price = value;
_IsDirtyTotalCash = true;
}
}
public double TotalCash
{
get
{
if(_IsDirtyTotalCash)
{
_totalCash = CalcTotalCost();
_isDirtyTotalCash = false;
}
return _totalCash;
}
}
}
Typically I try to put them on set since the value they generate will be stored internally and only need to be calculated once. You should only put calculations on get if the value is likely to change every time its queried.
In your price/quantity example, you could actually have a single separate method that recalculates the quantity when either price or quantity is set.
The first is better because:
That being said, putting the calculation in the setter effectively caches it, so if you run into a performance issue, that could be a useful change (at the expense of clarity).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With