A simple way to write logic and pass values ​between IFs

149 Views Asked by At

Is there an easier way to do this logical? It is used often and each time I have the impression that it is unnecessary.

if (x != y)
x = y;

In more time-consuming methods, you have to use variables so as not to recalculate them every time.

I think there has to be a better way than, for example:

var MyF = CheckSomething();
if (X != MyF)
 X = MyF;

I have a class name Person. It has a property Information.

If you change the value of this field, the system performs calculations which, based on the value set, changes the contents of other fields in the system.

The problem is that I don't want to change the contents of this field when it is identical to the value I have to compare.

Because it will slow down the program significantly.

And I wonder if there is an easier way than writing the above condition each time for each field that I want to check.

I can't change this class, all I can do is set the property value.

The problem is that there are hundreds of these classes with dozens of properties

(Thematic) Similar problem and solution :

string SomeValue = SetValue();
string NewValue;
if (SomeValue == null)
    NewValue = "NULL RECEIVED";
else
    NewValue = SomeValue;

Is the same as

string SomeValue = SetValue();
string NewValue = SomeValue ?? "NULL RECEIVED";

And this shortcut is what I'm looking for.

1

There are 1 best solutions below

0
Theodor Zoulias On

My suggestion is to use self containing blocks, in order to reduce the scope of the value-carrying variables to their associated if statements:

{ var v = GetInformation(); if (person.Information != v) person.Information = v; }
{ var v = GetAddress(); if (person.Address != v) person.Address = v; }
{ var v = GetPhone(); if (person.Phone != v) person.Phone = v; }

Another idea could be to use a generic EnsureValue method:

EnsureValue(person, x => x.Information, (x, v) => x.Information = v, GetInformation());
EnsureValue(person, x => x.Address, (x, v) => x.Address = v, GetAddress());
EnsureValue(person, x => x.Phone, (x, v) => x.Phone = v, GetPhone());

Here is the implementation of the EnsureValue:

public static void EnsureValue<TSource, TProperty>(TSource source,
    Func<TSource, TProperty> getter,
    Action<TSource, TProperty> setter,
    TProperty value,
    IEqualityComparer<TProperty> comparer = default)
{
    comparer ??= EqualityComparer<TProperty>.Default;
    if (comparer.Equals(getter(source), value)) return;
    setter(source, value);
}

I don't think that it makes your code more readable though.