DEV Community

Eric Ahnell
Eric Ahnell

Posted on

I Link Resources to Enumeration Constants; Why You Should Too!

When I make any sort of program that references non-code files, such as images or textual data saved with the code, I use enumerations whenever possible to force a 1-to-1 relationship between files and constants. This has a number of advantages:

  • Finding data your program declares, but does not use, is easier with tools that scan your code.
  • Finding data your program uses, but does not declare, will stop your code from compiling!
  • If you group your resources, using one enumeration per group prevents accidental cross-pollination, such as referencing an image intended for the user interface in the part of your code that displays charts.
  • Your resource loaders need to require an enumeration member to load a resource; without this, none of the above benefits will be realized.
  • Finally, if you ever scan your code for quality issues, having this system in place guarantees that an unused enum constant means the corresponding data file is also unused, making maintenance easier.

This applies to ANY type of program. I happen to use it for games in Java, but it works just as well in other types of programs written in other languages with enumerations.

Top comments (2)

Collapse
 
gregruminski profile image
Greg Ruminski

care to provide any examples of how that works?

Collapse
 
wrldwzrd89 profile image
Eric Ahnell

Sure I will! Using Java, since that's where I use this technique the most...

Say I have, in my assets collection: images, sounds, music. images has 5 sub-collections: avatars, items, monsters, objects, and ui.

There will therefore be 7 enumerations for all of these. An example for music, which has 3 files in it:
package com.mycompany.mygame.resourceloaders;
public enum GameMusic {
TITLE,
EXPLORING,
COMBAT
}

In order for the enumeration to do any good, a loader and a translator need to exist too. The loader is called by other parts of the code needing that resource:
package com.mycompany.mygame.resourceloaders;
public class MusicLoader {
public Music loadMusic(GameMusic which) {
...
}
}

The translator's job is converting enumerations into file names. I do this by loading a data file containing the file names for each of the music tracks (in this example), getting the numeric value for the enumeration constant, and using that as an index into the file names list.

As a nice side effect, attempting to ask the Music Loader to load something that isn't music, such as a monster image, will fail at compile time due to the arguments not being of the correct type.