Error checking…it’s kinda important
We recently had a dev meeting at my company, and we discussed the quality of our code. It seems as though with our rush to always push code out the door, our quality was slipping. We talked about taking ownership of our code (always important), more rigorous code reviews, and more thorough testing. I came out of it feeling fine, after all, my code is flawless. I continued to feel fine until about 5:30, when I found that the pagination on our mobile site was broken. Since I was on the team that put out the latest mobile version, I was less than thrilled.
Lo and behold, the error was from the back end team. I’M STILL FLAWLESS! All we had to do is roll back the back end changes, and we’d be back in business! That is, until I realized that a roll back might break my changes. Time to investigate!
Part of the deploy’s changes were to add color “swatches” under the products we sell. The server sent data to the React front end, which was then parsed and displayed. The relevant code:
Beautiful, right? We’re taking the siblings passed down from the server, and using map() to loop through. If we already have four, we’re doing nothing, and for the first four we’re returning the JSX with the appropriate classes tacked on. Simple right? Tested. Passed. Even QA thought it was snazzy. But what happens when the back end rolls back their changes, and siblings no longer exists?
Looking back, I realize my fatal mistake. I sometimes overlook the importance of error checking. My code may work in a perfect world, but the world isn’t always perfect. A partial roll back isn’t an option now, because doing map() on an undefined variable throws an error and crashes the app. Unfortunate.
A better approach would be to throw some sanity checks in there, so that a mistake elsewhere doesn’t bring the whole house down:
That one if statement at the top? That right there would save the app from crashing. We could even take it a step further and check to make sure it was an array. If I had taken the time to check the data coming in we could have rolled back the server changes and been on our merry way. As it is? Well, to be honest it wasn’t all that bad. They pushed out a hot fix to correct the pagination, so no roll back was needed anyway. But still, it showed me a fragile spot in the code. One that could easily be avoided if I had taken the time to add some simple error checking. So for today’s lesson I learned: don’t just write code that isn’t broken, write code that can’t be broken. Happy coding!