Why is &&
preferable to &
and ||
preferable to |
?
I asked someone who\'s been programming for years a
OK, on face value
Boolean a = true;
Boolean b = false;
Console.WriteLine("a({0}) && b({1}) = {2}", a, b, a && b);
Console.WriteLine("a({0}) || b({1}) = {2}", a, b, a || b);
Console.WriteLine("a({0}) == b({1}) = {2}", a, b, a == b);
Console.WriteLine("a({0}) & b({1}) = {2}", a, b, a & b);
Console.WriteLine("a({0}) | b({1}) = {2}", a, b, a | b);
Console.WriteLine("a({0}) = b({1}) = {2}", a, b, a = b);
produce the same answer. However, as you showed, if you have a more complex question so:
if (a and b and c and d) ..
If a
is not true and maybe b
is a function where it has to go off, connect to something, get this, do that, make a decision.. why bother? Waste of time, you know it's already failed. Why make the machine go off and do extra pointless work?
I've always used &&
because I put the most likely to fail first, ergo, less calculations before moving on when there is no point. If there is no way to predict less likely choices, such as you have a boolean to limit output of data, something like:
if (limit && !MyDictionary.ContainsKey("name"))
continue;
If it's not limit
, don't bother checking for the key, which could take longer..