To Enum or Not to Enum
Developer's Cave, Potential RPG June 25th. 2008, 12:46pmJava’s enum feature offers a powerful language capability: compile-time type checking of constants. In addition, enum constants make code much easier to read and debug. However, an enum represents hard-coded values, requiring application recompilation/redeployment to alter.
This conflicts with the mantra of code design taught to me: “Abstraction, abstraction, abstraction.” That is, a piece of software should be as general-purpose as possible.
Take, for example, the Potential RPG game engine. I’ve designed it to abstractly support MMORPGs, allowing game-specific content to be defined in external data files. This often precludes defining enum constants where they would otherwise make good programmatic sense.
For example, my game supports a variety of shop types (weaponsmith, alchemist, healer, etc.). Currently, these are loaded from a definition file, rather than being hard-coded in the software. Adding a new shop type can be done without modifying the code… almost (read on).
What I’ve discovered is that new content still requires logic and GUI code to be written against it. Therefore, the game must be recompiled/redeployed anyway, so why not just simplify things and hard-code enum constants?
Ideally, I’d love to make the game engine 100% abstracted from content. For example, all content-related code should be isolated into dynamically loaded classes, referenced by the content definitions. While it’s just me at the keyboard, simplification seems in order. (Unless someone is looking to invest in such a game engine…)
In summary, depending on the requirements of your project, just use enum constants unless the level of effort is worth the design/implementation/maintenance overhead. (Hmmm … now I’m talking like a software project manager.)




June 25th, 2008 at 2:50 pm
We ran into this on our current project. We wanted to make it possible to drop in a new data source without changing code, so we defined metadata files that describe the data structure. But we still have to write code to access those data sources and so we needed a way to enumerate them in code. And so that’s what we did. Now we maintain the data structure in two places.
Going to exclusively using enums now seems like the better choice.
June 25th, 2008 at 3:11 pm
Thanks for the corroborating report. I’m glad I’m not the only one.
I’m currently stripping out dozens of lines-of-code and replacing them with ShopType { WEAPONSMITH } … so much simpler. I love deleting crufty code.
June 26th, 2008 at 3:21 pm
As a counter-example, I’m still loading terrain types from an external config file. This is simple enough, because the terrain logic (just a navigability check, at this point) does not need to know the specific terrain type.