Should I write out computed vars that all depend on one other var, or should I assign them as normal vars in that single var's setter?
https://softwareengineering.stackexchange.com/questions/362052
-
24-01-2021 - |
質問
I'm using Swift, but I understand computed properties are a thing in a few other languages as well. I have the following case:
- var
bar
in classFoo
is changed throughout program flow. - vars
a
,b
,c
andd
are constrained tobar
's value so defining them as computed properties is a clean way to handle that. - the constraints are simple calculations that take
bar
and output a value
I can write the formula in the getter of each of the individual vars (the formulas vary slightly), or I could have the vars be normal properties and just assign them in bar
's set.
Which is more preferable? Is there anything more to consider than style?
解決
Yes, if you move the computation to the getter of these properties, then it will be performed only when you actually read those computed properties, and not every time whether it's needed or not. Whether that makes a difference or not depends entirely on how common the access is and how costly the computation.
他のヒント
Another option based on @Killian's answer would be to keep the calculation in the getter, but cache it, in order to avoid the calculations in every read.
Here's some code in C# to illustrate this:
public int? _cachedA = null;
private int _foo;
public int Foo {
get { return _foo; }
set {
_foo = value;
_cachedA = null;
}
}
public int A {
get {
if (_cachedA == null) {
_cachedA = magical_calculation(Foo);
}
return _cachedA;
}
}
It's a classical time vs. space trade-off.
If a
, b
, and c
are trivial to derive from bar
, then it's easiest to just have them be computed properties that derive a value from bar
.
If they're expensive to compute, and small enough that they're worth the memory to cache, then you should make them stored properties. Their value should computed and cached either when bar
is changed, or when they're accessed, whichever is less frequent.