Pattern matching as a tool for refactoring

Pattern matching is useful even if you don't end up using `match` because it helps you reason about your code

A small example

Take the following snippet, slightly simplified from the original:

Currently query looks like this:

I need to refactor query to be like this:

We know that the params map has at least the :tenant key, and it might have a :id key as well. Knowing this, we can identify 2 possible patterns that the data could be in:

  1. Contains both :tenant and :id
  2. Contains just :tenant

Pattern Matching to the Rescue

A perfect solution for this is pattern matching

The match function from core.match first takes a map to match on, in this case params. Then, it takes a series of patterns and returns. In the first case, we want to match a map that has both :tenant and :id, and we want to extract the values for each key as t and d respectively. Then, we put that in a new map with :type :admin and return the entire thing to the caller. The second pattern, we only extract :tenant, and the third is a fail-safe in case the caller forgot to add :tenant for whatever reason (according to the spec, :tenant is technically optional). _ in this case is a wildcard.

Nota bene: we have to order our matches from most-specific to least-specific. For example if we put the {:tenant t} pattern first, then it could trigger a match even though there is a :id present.

A Simpler Way

Now you might look at this and say, “it sure looks like you are repeating yourself a lot.” In which case you would be right, and there is a simpler way to write this code:

This does the same thing as the pattern matching. select-keys will take out :id and :tenant if they are present in params, and then we merge those keys with {:type :admin}. We can’t use get in this case because, according to the spec, if the keys are in the final map, then they must not be nil, and get will return nil if it doesn’t find the key in the params map.

However, it’s very hard to see the succinct answer we came up with from the first code snippet. In this case, going through the exercise of pattern matching is valuable even though we didn’t end up using match because it made the structure of the data explicit. In the original snippet, the data structure was there, but it was difficult to see clearly in all the moving parts.

The full refactor

At the end of the day, here is the full progression of refactoring:

—Ben Sima, 2017.03.31