Front-End Diagnostics (2 Part Series)
In looking through some client code recently, I came across a pattern that was similar to something I had used before. While I could see the similarities, the toggle for the pattern was radically different.
In creating a script-engine and parser in the past, I used console logging to allow for simple diagnostic information to be displayed. Not wanting the logging to show up in production and at the same time not wanting to remove the logger and testing information I had created, I settled on creating a simple root-level boolean that the logger would watch for.
var forceTesting = false;
With this code in place, I was able to simply run the following in the console, then use the site while observing the output:
> forceTesting = true
I try to use the Console API efficiently; if you haven't looked into the Console API, take some time and do so, because there's a lot of functionality available. Here are some of the parts of Console API that I used ... often having developers saying, "I can do that?"
Logs the number of times that this particular call to count has been called. This function takes an optional argument label.
Creates a new inline group in the Web Console log. This indents following console messages by an additional level, until console.groupEnd is called.
Displays tabular data as a table. It logs data as a table. Each element in the array, or enumerable property if data is an object, will be a row in the table.
Starts a timer that can track how long an operation takes. Each timer is given a unique name. When console.timeEnd is called with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started.
Now let's look at the client code I came across.
Within the client code, I found ...
var forceTesting = JSON.parse(localStorage.getItem('forceTesting') || false);
This allowed their developer to execute something familiar and their code was configured, like mine, to show logging or use a different dataset.
> localStorage.setItem('forceTesting', true)
The true genius of this code became apparent to me very quickly. Some simple console tests confirmed my thoughts.
This code not only turned on a "developer mode," it set it consistently for my environment. Clearing the cache using Chrome's "Empty cache and hard reload" DID NOT remove the localStorage forceTesting state. I was still in my developer mode.
My pattern suffers from the simple fact that I have to change the global variable's value every time I reload the code. This new pattern allows the state to be maintained throughout a development cycle!
You're one click away
Level up every day