I was going to do this one thing, but I ended up doing something else. I had set a goal for me last night to try and apply SOLID on a small JS project of mine. Extremely small. It's a NodeJS twitch-chat bot that helps viewers playing a twitch-integrated game in the stream.
It was quite simplified already as I had created the game-related stuff in it's own API class as an interface for getting data from the game's public API. So I set out to refactor the part of the code that involved keeping track of userstates of the players.
Reason for that is to provide an extra service for them to detect when the game is getting out of sync and the servers are not getting any more updates. This is a bug in the game and architecture itself and will be remedied at one point by the developer making the game, but for now, I provide this as a detection-service for the viewers to leave and rejoin the game to not lose progress.
So that's the premise.
What I have is a simple in-memory array of userstate objects that I update with a hash value of their in-game statistics. If that statistic is not moving, despite them doing something in the game that should actively be updating those values, then something is up. So there's a detection function that gets any previous value from the array, if not, create it in the array. Then initiate a check against the API and compare hash values. If it has changed, all is fine. If not, message the player that they should be leaving/rejoining the game.
This was all done in one function of about 50 lines in total with loops that accessed the statistics array 3 different times and modified state in these. Reason I needed to have state change was because since messages that could trigger the check come in asynchronously as well as the function itself runs an asynchronous action. So not to trigger multiple checks, I need to maintain a boolean, per player, that prevents that.
So to the jist of this post. I created two ES6 classes one for the base object UserState and an orchestrator/container UserStates that had wrapper functions for updating a user object in the array and UserState had functions to flag it being updated and when it's done. It could also have had the md5hash calculations, but I recon I will use those elsewhere so I didnt include that in there.
With all of that refactoring, the function that now did the progress check went from 50 lines down to 15-20 lines (can't remember now, not at the computer) and the code could almost be read like it was a normal sentence.
So with that said, use whatever transpiler you have available. Online or offline, and create your classes for javascript. I can highly recommend it. Not only does it make the code cleaner and more readable, but it also makes it easier to test.
Top comments (0)