Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if values are different

Tags:

c#

boolean

Let's say I have 4 variables

bool value1 = false;
bool value2 = false;
bool value3 = true;
bool value4 = false;

and they all don't have the same value (all are true || all are false)

I have found 2 approaches, anyway none of them looks easy to understand.

bool areDifferent = !(value1 == value2 == value3 == value4);

and

bool areDifferent = new[] { value1, value2, value3, value4 }.Distinct().Count() > 1;

Question: Is there a other approach, which is better in terms of readability / understandability?

like image 659
Impostor Avatar asked Dec 03 '22 09:12

Impostor


2 Answers

For readability and understanding, I would swap the logic. When you check if values are different it's not clear - all values should be different (consider integer values 1, 2, 3), or values could be equal, but there is at least one different value (1, 2, 1)? When you check if all values are equal it's always clear.

And I would extract this logic to the nicely named method (you can even make it generic if you want):

public static bool AllEqual(params bool[] values)
{
    if (values.Length == 0)
       return true;

    var first = values[0];
    for (int i = 1; i < values.Length; i++)
        if (values[i] != first)
            return false;

    return true;
}

And usage

var notAllEqual = !AllEqual(value1, value2, value3, value4);

With declarative approach your code describes what you are doing instead of telling how and leaving the reader on its own to understand what.


Update: If you always deal with four boolean values, the simplest way to check if they are not all equal is

(value1 ^ value2) || (value2 ^ value3) || (value3 ^ value4)

But in terms of readability, any imperative approach is worse than declarative

like image 183
Sergey Berezovskiy Avatar answered Dec 11 '22 12:12

Sergey Berezovskiy


Maybe Linq is declarative enough?

var values = new[] { false, false, true, false };
bool notAllEqual = values.Any(x => x != values.First());

Alternatively:

var values = new[] { false, false, true, false };
bool allEqual = values.All(x => x == values.First());
if (!allEqual)
{
     // They are different
}
like image 29
Ulf Kristiansen Avatar answered Dec 11 '22 10:12

Ulf Kristiansen