CodeSOD: Enumerating Your Plants

Usually, we don't pick on game code, as it's frequently bad because of the time constraints under which it's developed and because the concerns are more around "making a fun, performant game," and not "writing good reusable code".

But there are some egregious exceptions, like what happened to Patrick. He was handed some C# game code, and told, "Good luck!"

This particular block lived in a file called banana.cs. Does this game have anything to do with bananas? It does not! It has to do with zombies. No, it is not Plants vs. Zombies, though given the botanical flair in this code, perhaps the author was a fan?

One module of the game uses integers as the ID values of enemies. One module uses strings. No one uses enums. So when you want to convert the IDs to the appropriate type, you need to call enemyIdNumToName, which I want to stress- is not the display name of the enemy.

public static string enemyIdNumToName(int inId) { string returnData = ""; switch(inId) { case 0: returnData = "Radish"; break; case 1: returnData = "Tomato"; break; case 2: returnData = "Orange"; break; case 3: returnData = "Banana"; break; case 4: returnData = "Strawberry"; break; case 5: returnData = "Carrot"; break; case 6: returnData = "Watermelon"; break; case 7: returnData = "Grapes"; break; case 8: returnData = "Broccoli"; break; case 9: returnData = "Bell Pepper"; break; case 10: returnData = "Coconut"; break; case 11: returnData = "OneGrape"; break; } return returnData; }

This code takes an integer, and converts it into a string. The integer has no inherent meaning. The string has no inherent meaning. This function does no validation to confirm that the integer is in the correct range, and if it's not, the switch doesn't sanitize or protect it at all. Invalid inputs don't get trapped or even logged. And no, the downstream code doesn't play nice if you pass it an empty string.

Which, finding this block did help Patrick diagnose a crash (an integer that was out of range was getting passed in), so at least it served some purpose.

[Advertisement] ProGet’s got you covered with security and access controls on your NuGet feeds. Learn more.

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published.