Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it wrong to alter the value keyword within a setter?

Tags:

c#

I have a setter that needs to process the new value with the old value. However if the value is < 0.1 it needs to be set to 0.1.

I could create a newValue variable based on the value keyword but this seems a bit wasteful and within the processing section it is not immediately obvious what newValue is.

Likewise if I looked at the code I would expect 'value' to be what was passed to the setter rather than something manipulated.

What would be the best way to write this, use newValue or the value keyword?

public double NumberValue
{
    get => _numberValue;
    set
    {
        if (value < 0.1) value = 0.1;

        var multiplier = value / _numberValue;
        foreach (var item in Items)
        {
            item.SomeValue = item.SomeValue * multiplier;
        }
        _numberValue = value;
    }
}

My method has ended up like this which is a much neater solution

public double NumberValue
{
    get { return _numberValue; }
    set
    {                
        var newValue = Math.Max(0.1, value);
        ProcessValues(newValue);
        _numberValue = newValue;        
    }
}
like image 742
Matt Norrie Avatar asked Jan 26 '23 15:01

Matt Norrie


2 Answers

Here's what I would do:

public double NumberValue
{
    get => _numberValue;
    set
    {
        _numberValue = value < 0.1 ? 0.1 : value;
    }
}

Another way suggested by @Matthew in the comments would be to use Math.Max:

public double NumberValue
{
    get => _numberValue;
    set
    {
        _numberValue = Math.Max(0.1, value);
    }
}
like image 151
Lews Therin Avatar answered Jan 29 '23 14:01

Lews Therin


Technically, it really doesn't matter. What differences there are are about readability.

Here, I'd probably do _numberValue = value < 0.1 ? 0.1 : value; myself because all of the logic is clear and this rather idiomatic statement covers everything.

If the logic was more complicated then I might favour overwriting value or I might favour declaring a new variable based on just how much more complicated it is. In particular I might favour a new variable if there was more than a page of code so it wasn't clear while looking at the bottom of the setter that value had been overwritten.

In favour of overwriting also is that it's a matter of clamping value to within a range. Some more disconnected possible uses of overwriting are not going to be as readable.

As with all readability matters there isn't a perfect answer and there's always a tension between the readability advantage of being short and the readability advantage of being concise.

like image 31
Jon Hanna Avatar answered Jan 29 '23 16:01

Jon Hanna