Just a quick question so as to know if there is a better practice between updating the value of a property with a method that gets called everytime the value needs to be changed or just to do it in the getter.

For instance between this:

        public double Balance { get; private set; }

        private void UpdateBalance()
        {
            if (Payments.IsNullOrEmpty())
            {
                Balance = 0;
            }
            else
            {
                double amountSum = 0;
                foreach (Payment payment in Payments)
                {
                    amountSum += payment.Amount;
                }
                Balance = amountSum;
            }
        }

And this :

        public double OtherBalance
        {
            get
            {
                if (Payments.IsNullOrEmpty())
                    return  0;
                double amountSum = 0;
                foreach (Payment payment in Payments)
                {
                    amountSum += payment.Amount;
                }
                return amountSum;
            }
        }

The only difference I can think of is one of performance, since in the first case the getter runs through the whole list every time we try to get the value of the property. However, you don't need to worry about calling the Update method every time you do a change that might impact the value of the property like in the second option. Is that difference really significant ? Beyond that, is there any reason to chose one option over another ?

Thanks in advance

2 Answers

1
ehsan kiani On Best Solutions

Well in first method for reading the balance you should call the getter again and in the second method there is no balance at all, personally I prefer second method because it's generate the value at the call time so you can be sure that it is always updated and it doesn't need to call a function and then read the value so it's cleaner and more maintainable.

1
bolkay On

To add to Kiani's answer, if you don't mind using Linq, you could turn your code to a one liner.

private double Balance=>(!Payments.Any())?0:Payments.Sum(t=>t.Amount);