Search code examples
c#model-view-controllermodelbusiness-logic

How can i make my business logic only execute once, so it alters the object only once


I have the following business logic:

public decimal Price
        {
            get {
                if (OrderSize == Size.Small)
                {
                    _price = decimal.Multiply(_price, (decimal)0.8);
                }
                else if (OrderSize == Size.Large)
                {
                    _price = decimal.Multiply(_price, (decimal)1.2);
                }
            return _price;
            }
            set {
                _price = value;
            }
        }

The price should be only changed once based on the chosen OrderSize. When this order is retrieved it calculates the price again which is obviously not what i want. What is the best way to make this only execute once?


Solution

  • You're not far off. Don't assign the _price variable again, just return the calculation.

    public decimal Price
    {
        get
        {
            if (OrderSize == Size.Small)
            {
                return decimal.Multiply(_price, (decimal)0.8);
            }
            else if (OrderSize == Size.Large)
            {
                return decimal.Multiply(_price, (decimal)1.2);
            }
            else
            {
                return _price;
            }
        }
        set
        {
            _price = value;
        }
    }