Using XOR to write concise conditionals
It's not uncommon that I sometimes write if
statements where the overall conditional is true when both conditions are true or both are false.
As an example, let's say I'm validating input from an API call where I'm updating information on a receipt that was created in an accounting/invoice system, where if one property is provided, another property must also be provided:
# Contains user-provided information from a request
updateRequestPayload = {...}
if (updateRequestPayload.currency is not None and updateRequestPayload.total is not None) or (updateRequestPayload.currency is None and updateRequestPayload.total is None):
# Request is valid
else:
# Request is not valid
Pseudocode
That's not the easiest on the eyes.
One way to write that conditional more concisely is using XOR:
hasBothProperties = updateRequestPayload.currency is not None and updateRequestPayload.total is not None
hasNeitherProperties = updateRequestPayload.currency is None and updateRequestPayload.total is None
if bool(hasBothProperties) ^ bool(hasNeitherProperties):
# Valid
else:
# Invalid
More pseudocode
The ^
tends to be the bitwise XOR operator in other languages too. Here's an example of how this appears in Javascript:
const request = {currency: "CAD", total: 500}
const hasPropertiesSet = !!(request.currency && request.total)
const hasNeitherProperty = !request.currency && !request.total
console.log(hasPropertiesSet ^ hasNeitherProperty); // Returns 1 which is our truthy value.
and you can see in Rust's docs they have the same thing.
Like what you've read?
Subscribe to receive the latest updates in your inbox.