1

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 class Foo is changed throughout program flow.
  • vars a, b, c and d are constrained to bar'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?

3 Answers 3

3

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.

2
  • 1
    Writing them in the getters of the vars would mean running the formula every time the var is accessed, while putting it in bar's setter means running the formula only if bar changes, right? Ooooh I think you just opened my eyes, I just need to figure out what happens more often, changes in bar or reads of the other vars, and decide based on that result.
    – Kevin
    Dec 8, 2017 at 15:38
  • @Kevin also look at lazy properties they are calculated once and can be read many times but if the underlying changes?
    – mmmmmm
    Dec 11, 2017 at 15:27
1

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;
    }
}
-1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.