In this tutorial, you will learn a technique that if used correctly, can help you write code that contains fewer bugs. When writing any software, writing testable code is key. Unit tests should guarantee that the code you have written does what it expects you to do. There are many different types of ways of testing your code and in this tutorial, you will learn why writing guards within your code are important and how you can start writing your own guards in a clean approach.
What Is A Guard?
A guard is a check that guarantees that all your function parameters meet your minimum requirements in order for you to guarantee that the function can execute correctly.
When you add guards to your functions, what you're declaring is a set of assertions that must always hold true for that function to execute. No parameters can ever make the system behave in an unexpected way, if it does, an exception will be thrown. An example of a guard check could be that parameters should never be false, or that a parameter has to meet certain criteria. If this is not the case, an assert is raised.
If you do this for every function you write, you will massively reduce the chance that your app can get into an unexpected state.
If you're sold on the importance of guaranteeing that your functions can only be called with valid arguments, then the next question is how to start implementing it? Your first instinct might be to start writing lots of your own guards, maybe something like this:
There are a few issues with this approach. One, this breaks the DRY principle. You'll end up copying this code throughout your codebase. If you want to change, say where the guard errors are logged, then you will have to go through your whole codebase and update it. This is bad architecture.
Your next instinct, might also be tempted to write something custom, but why reinvent the wheel when you don't need to?
Instead, I recommend using 'Invariant'. More information about Invariant can be found here. You can install Invariant, via NPM:
After it is installed, you can then use it to protect the parameters of your function, like so:
The cool things about Invariant are that when running your app and process.env.NODE_ENV is not production, the guard will be mandatory. If process.env.NODE_ENV is set to production, the message is optional – so they can be hidden. This way you can write tests for your code, test it thoroughly in development and when you push it to prod your app will not break.
I've used Guards in my code for years to check props get set correctly. During this time guards have helped me catch hundreds of bugs. I'm hoping by now I've convinced you to start using them, enjoy!