Introduction
I struggle once in a while over some complicated if
-elseif
-else
constructs that have a more concise alternative: use of the xor operator (means: exclusive-or) that many languages provide.
This tip shows the use of xor on an example of a conditional toggle function. Such functions may be used in automated GUI tests where e.g. in a tree view a sub-tree has to be opened if it is not yet open, or has to be closed if it is open.
It is a trivial tip, but it seems that many people either don't know of it or it does not occur to them to use it.
Using the Code
Assuming you had to write the following function:
void ClickIfNeeded(ToggleButton button, bool pressed)
{
...
}
The xor implementation provides in my view a cleaner implementation compared to the naive implementation:
Naive implementation |
xor based implementation |
void ClickIfNeeded(ToggleButton button,
bool pressed)
{
if (button.IsPressed)
{
if (!pressed)
{
button.Click();
}
}
else
{
if (pressed)
{
button.Click();
}
}
}
|
void ClickIfNeeded(ToggleButton button,
bool pressed)
{
if (button.IsPressed ^ pressed) button.Click();
}
|
The Exclusive-Or operator:
- the xor operator has for C, C++, C#, etc. the following sign:
^
- xor gives
true
if exactly one of the operands is true (hence: exclusive or)
- xor gives
false
if both operands have the same value.
i.e. in the example above: only click the toggle button if it has not yet the requested pressed state.
History
V1.0 |
2013-01-12 |
Initial version |