Should access to C # use a private variable or compute on the fly?

What is the best programming practice and why?

I have a class like this:

class data {

    public double time { get; internal set; }
    public double count { get; internal set; }
    public average_count { ... }

}

Where average_count should be read_only and give a quantity / time calculation.

Is it better to write an accessor like:

public average_count { get {

    return (time == 0) ? 0 : (count / time);

}}

Or I need to do something like:

private _avg_count;

public average_count {
    get 
    {
        return _avg_count;
    }

    internal set
    {
        return _avg_count;
    }
}

Where is _avg_count updated when the time and quantity are set in the inventory?

It seems that the former is easier to read, but may be slower if it is often accessed by middle_count. Will compiler optimization be negligible?

+3
source share
8 answers

. , , () () , .

, , .

+13

, , , . , "" .

1.

Skilldrick , , , :

[R] eadability .

, , - true, - . , - , , , ( , , ).

, . - , ; , .

2.

0xA3 , : , .

, , , . int? , , , int a bool ( - 64 40). data, - , , 32 .

3.

, , , , , , , , .

, , , , , .

+5

, average_count count time. .

+4

, , , : , , . :

class Foo
{
    int? _cachedResult = null;

    int _someProperty;
    public int SomeProperty
    {
        get { return _someProperty; }
        set { _someProperty = value; _cachedResult = null; }
    }

    int _someOtherProperty;
    public int SomeOtherProperty
    {
        get { return _someOtherProperty; }
        set { _someOtherProperty = value; _cachedResult = null; }
    }

    public int SomeDerivedProperty
    {
        get
        {
            if (_cachedResult == null)
                _cachedResult = someExpensiveCalculation();

            return (int)_cachedResult;
        }
    }
}
+4

; , . , , - , , , .

.

+1

. , , , . , (, average_count), , , .

( ), Pascal #, .

+1

?

Depends on what you consider "significant." Reading is varaible pretty fast. The division of two numbers is pretty fast. In fact, depending on what is in the RAM cache, reading variables may take longer than doing a split.

Use the first method. If it seems slow, then consider the second.

0
source

If you care about thread safety, it might be easier to make the second option, rather than the first.

private double _avg_count;
static readonly object avgLock = new object();

public double time { get; internal set; }
public double count { get; internal set; }


public double average_count {
    get 
    {
        return _avg_count;
    }


}

private void setAverageCount()
{
    _avg_count = time == 0 ? 0 : (count / time);
}


 public void Increment()
 {
     lock (avgLock)
     {
         count += 1;
         setAverageCount();
     }


 }


 public void EndTime(double time)
 {
     lock (avgLock)
     {
         time = time;
         setAverageCount();

     }
 }
0
source

Source: https://habr.com/ru/post/1761368/


All Articles