Answer the question
In order to leave comments, you need to log in
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;
}
}
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question