Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logic in property getters [closed]

Tags:

c#

properties

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.

like image 781
Jan Paolo Go Avatar asked Apr 04 '16 13:04

Jan Paolo Go


2 Answers

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.

like image 145
Sebastian Lenartowicz Avatar answered Oct 17 '22 21:10

Sebastian Lenartowicz


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.

like image 2
Rahul Tripathi Avatar answered Oct 17 '22 22:10

Rahul Tripathi