Let’s imagine you’re on a large project. You have the following limitation - ES5 Javascript.
Now, what happens in large codebases with 20k+ lines? They will end up with files called config.js
and contact_info.js
and environments.js
, etc. Reference files that are frequently used.
In my case, our project has some code that (for example), shouldn’t run in production, but it should run in a development environment.
We had a file that looked like this:
So here’s how we typically would use this. Let’s say we don’t want a certain part of code to run if we’re in the production
environment (a pretty common need).
Using Node.js to get the ENV
environmental variable, we would check like this:
If you’re saying dude, just use .includes()
- remember, ES5!
Okay, so let’s say we have an urge to make this more readable across the codebase. What’s one way to solve this?
Why, sure, let’s introduce some more overhead to this process! :)
Let’s modify that object we worked with earlier.
We’ve added a getter to the object called is
. is
is an object that will contain pre-computed responses about the environment we’re working in.
In the end, we want to be able to make a call like this: environment.is.dev
. The logic for a self-aware object is as follows:
The whole thing ends up looking like this.
Our developers can now do something easy when they’re trying to determine where the hell their code is running.
This sort of self-aware object makes working with constant data much simpler. If you know a cleaner way to do this, email me :) I’ll give you a prize. The prize is me sending you an email back btw.