Pattern Matching 😛
Ok, that’s a tad too many conditionals … Hmmm!
I have felt this way before too! but no worries here comes pattern matching to the rescue lets use Elixirs pattern matching to explore this.
Say we have a function that needs to check if a user is a paid user or a free user.
Now this works completely fine but as your application grows and suddenly you have to tack on a bit more data on a user and user a few more parameters to validate as you now have multiple tiers in your application this can get very brittle and problematic to follow and handle.
It’s not all doom and roads to hell 😃
Take a breath and embrace Pattern Matching.
Now let’s use Elixir’s pattern matching as an example,
Pattern matching applies anytime we need to bind values to variables for example when calling functions and passing them parameters — Mike Stark
To use the above we just invoke
validation = validate(user)
Considering that both ‘forks’ in the logic are handled separately now it becomes very easy to fine tune and modify them without messing with the other forks allowing you an amazing amount of flexibility.
Do you use a language that supports pattern matching?
Let us know in the comments
Back to code 😛