1Q91
1Q91

Reputation: 23

How to avoid hardcoding file-references?

My Code:

I'm currently developing a game and throughout several different parts of the code I'm using some resources (Images/Sounds/Animations etc.). To avoid loading the same resource twice I wrote a ResourceManager, that returns the wanted resource if I pass a string to it.

Here's an example:

Image myImage = imageManager.getImage("princess");

This way I can reference a resource without knowing the name of the file or position of it, when I want to use it. The trick here is that I have to load the images before I can get them like so:

imageManager.loadImage("res/princessImage.png", "princess");

This creates the ImageObject from the given file, and stores it into a HashMap with the given key.

My Problem:

I really don't want to hardcode the paths to these resources, because I'd have to change the sourcecode every time I decide to move or rename any of the resource-files.

A possible solution (?):

I thought about creating another HashMap that reads some kind of configFile and maps the in-code-resource-names to the resource-paths in a HashMap. The file would look somewhat like this:

princess: res/princess.png
hero: res/hero.png
sword: res/items/sword.png

This way I could use resource-names like "princess", "hero" or "sword" safely and don't worry about their position on the hard drive while I'm coding. Whenever I move or rename a resource-file I just update the path/name in this configFile and everything would be fine.

On the other hand I think it's pretty ugly to have one giant file that maps every in-code-resource-name to a path. This could result in one giant String to String HashMap which I'd have to store in the ResourceManager aswell. Things could get pretty confusing/unclear.

Does anyone have a better solution for me?

I'd really appreciate your help,

Thanks :)

Upvotes: 1

Views: 571

Answers (1)

Liggy
Liggy

Reputation: 1201

Using a config or resource file as you described is a fine approach. Instead of populating a HashMap, though, consider using ResourceBundle or PropertyResourceBundle. It is designed to hold/access such things. http://docs.oracle.com/javase/6/docs/api/java/util/ResourceBundle.html

Upvotes: 3

Related Questions