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.  

Introducing Invariant

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:

  
function MyFucntion(one) {
  	if (!one) {
       return new Error('error');
    }
}

There are a few issues with this approach. One this breaks the DRY principle. You'll end up copying this code throughout your code base. If you want to change, say where the guard errors are logged, then you will have to go through your whole code based 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:

npm install invariant

After it is installed, you can then use it to protect the parameters of your function, like so:

var invariant = require('invariant');

function MyFucntion(one) {
	invariant(one, 'My Error Message');
}

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 and I can say that using guards and writing tests to check those guards, usually results in my finding bugs that would have slipped through. I'm hoping by now I've convinced you to start using them, enjoy!