Z
Z
Zaur Ashurbekov2017-10-30 16:38:14
C++ / C#
Zaur Ashurbekov, 2017-10-30 16:38:14

How to provide correct access to protected fields in this case?

Hello Toaster!
While working on the next task, he made a bug (did he || write ?) and fixed it himself. And then I realized what a dangerous thing I had written and wondered how to write it correctly, so that if someone works with this code, they would not step on the same rake.
There is a code:

public abstract class A
{
        protected Foo Bar = new Foo();
        protected bool isDataActual = false;
        public Foo bar
        {
            get
            {
                if (isDataActual)
                {
                    return Bar;
                }
                else
                {
                    calculateData();
                    isDataActual = true;
                    return Bar;
                }
            }
        }
}

What was the bug? In my descendant class, during the execution of calculateData(), instead of calling Bar, I turned to bar, which again called calculateData, and so on until the stack overflowed.
The question is, how in this case it was worth writing the code so that other programmers in their descendant classes could not make the same mistake. The case is typical, there must be some generally accepted solutions.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
cicatrix, 2017-10-30
@zaurius

In general, calling a calculation from a property getter is bad. And yours is just one of the reasons.
From my point of view, maintaining the current state of the class is the task of the class itself. If recalculation is required, then it must be performed when the state of the class changes (at the moment the parameters for recalculation are changed), and not at the first attempt to read the result (however, there are different cases).
Secondly, the naming convention - all local fields must differ from the name of external properties. For example, I prefix all local class variables with the m_ prefix (in your example, it will be m_Bar.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question