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?
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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With