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:
That's not the easiest on the eyes.
One way to write that conditional more concisely is using XOR:
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.