Skip to content

Using XOR to write concise conditionals

Erica Pisani
Erica Pisani
1 min read

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.

rustpythonjavascripttips-and-tricks

Comments


Related Posts

Members Public

How to install nvim-ufo in LazyVim to enable foldable code blocks

A feature that I've found myself missing since making the switch to Vim as my editor of choice is the ability to easily fold and expand code blocks. I know this functionality is included in Neovim, but I couldn't understand the native implementation enough to use

How to install nvim-ufo in LazyVim to enable foldable code blocks
Members Public

Git Log's Hidden Gems: Using -S and -L for Powerful Code History Search

Ever needed to track down when a specific piece of code was first introduced in a project? As part of some refactoring I had to do recently, I needed to do just that for a variable on a Django model. I was already familiar with the basic git log command,

Git Log's Hidden Gems: Using -S and -L for Powerful Code History Search
Members Public

Fixing "No preset version installed for command poetry"

Poetry is a packaging and dependency management tool for Python, and a tool that didn't exist when I worked with Python many years before I started working at Float. I also hadn't been exposed to asdf, which is a handy little tool for managing multiple runtimes.