BLOG

Wow, I got lucky there

How my messed up code ended up saving me from regression

1/18/2018Time to read: 2 min

I have to admit, I made a lot of bugs.

I work in the UI Infrastructure team and one of my main responsibility is to refactor existing code and extract out common utilities used in many places. This is a risky job in my opinion. Unlike other people who mostly work on a subset of the code, I am working with the whole code base.

Our company has about 20 releases each year. Today, I found that I did something stupid in the last release that actually saved me from another potential bug. As we all know, once the code is out in production, it becomes very hard to fix.

We have an endpoint that is used to send through Ajax with all the information about the user once s/he logins in. One of my tasks was to save the result in browser session storage. User's information includes user's locale, language, and timezone, etc. Other parts of the code depend on that information. In the last release, I changed all other places to check if session storage contains a specific value. If it does, that means the ajax has already returned, and session storage is initialized with all the data.

This sprint, I found that this was a stupid idea. When the user changes their language and locale settings on their profile page, our app simply does a refresh. However, refresh DOES NOT clear session storage. When the page reloads, the old data in session storage is used and causing some date formatting issue, because it's using the old locale (however, this is a rare use case, so we decided to fix it in next release).

A better way (or not) to check if session storage is initialized yet, is to have a global variable on window (Ewww, global variable) storing the state of session storage, like isSessionStorageInitialized. I set it to true when the ajax returns and session storage is initialized. I committed the code. Not long after, it broke the app.

Turns out that from our app, a user can open up a child window. Child window shares the same domain as the parent window, so they also share the same session storage. But since it is another window, they don't share the attribute defined on the window object. Inside the child window, isSessionStorageInitialized is never set to true, so nothing can use the session storage.

If I had used the better solution last release, I would have to fix the child window issue in production.

In retrospect, I don't know if I should feel lucky or sorry. Perhaps I should have done more research about session storage to understand it's quirks. But anyway, I just feel that is an interesting experience. I can have a good sleep tonight without worrying about production issue.

Create a Null safe world using JavaScript Proxy
How I Broke the Routing System of Our Enterprise App