How much logic is too much for a property getter? For example, I have code which looks like this:
public double value
{
get
{
if (condition1
|| condition2
|| condition3
|| condition4)
{
_value = anotherValue;
}
return _value;
}
}
I have read various posts that say the code inside properties should not be expensive. But the term 'expensive' is a bit vague for me.
Generally speaking, in OOP a getter (setters too) should be a trivial operation. What you've posted above is trivial, depending on what the conditions actually are.
You mentioned that "expensive" is a vague term to you. An operation being computationally expensive means that it will take a long time to complete (usually because it has to complete a lot of computations -- that's an oversimplification, but a decent approximation). For instance, consider:
if (a == 5
|| b == true
|| c == "FOO!"
|| d == 3.14159)
{
_value = anotherValue;
}
return _value;
In this example, the conditions are trivial, and your program will crunch through this block near-instantaneously. On the other hand:
if (some_slow_function())
{
_value = anotherValue;
}
return _value;
Assuming some_slow_function does actually run slowly, this block will take a long time to return _value
, making it no longer trivial. If this getter is called often, some_slow_function
will be called often as well, causing it to bottleneck your program and cause it to run slowly.
The MSDN says:
Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as though they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily while still providing the safety and flexibility of methods.
So as long as your Property getter is idempotent and performing fast(i.e, not creating any performance bottleneck) it is fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With