DEV Community

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

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.