I had a thought while I was working on the game Alone In the Office (my LudumDare 22 entry). I wonder if I can make this code look more beautiful. So I went through and refactored the code. Okay, so I cleaned it up. There was cleaning to be done. But, I wondered if I could find any useful tid-bits of information about what other people do to keep code nice. I found this article and I noticed B. B is to return the immediate value of a boolean test instead of testing if the boolean test returned true or false. Mind you, in certain cases you DO need to check. In the cases of some of my code, I did not. B is the one thing I apparently overlooked in programming over the years. It’s interesting how I never noticed it to say the least. Anyways, upon reading to the end I find this article.
Called, “abolish the switch statement”, this article goes on to explain how to inaccurately use a switch statement and why it looks ugly. Then suggesting the use of maps. As an ex-web programmer and game programmer, I can tell you something that’s right and wrong about this. What’s right, switches are used improperly by inexperienced programmers. That’s especially true since I’ve taught and am still teaching programming to people. What’s wrong, everything else, including the solution itself. This article takes into no account values that go into the objects when declared nor the fact that switches are faster, especially on mobile devices.
In a game, each object has methods it calls based on the action it’s performing. *Unless you’ve got some super-abstract game model that allows you to handle actions outside the object, you aren’t going to make a new class for an action. Therefore, making their solution fail immediately. Take a look at this abstract example showing the proper use of switch i.e. not using magic numbers and why this looks as nice as the code could ever be.
Continue reading “Nice code and switches”