HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Is using java enums to store filepaths good practice

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
practicejavastoreusinggoodfilepathsenums

Problem

I'm working on an android application, but this is basically plain 'ole java.

The aim is to do the right thing and not repeat myself.

public enum Datafile {
    ACTIVITIES() {
        @Override public String filepath() {
            return "activities.yaml";
        }
    }, 
    OPEN_LOOPS() {
        @Override public String filepath() {
            return "open_loops.yaml";
        }
    };

    public abstract String filepath();
}


Later on, when I want to edit the file I try this

File file = getDataFile(Datafile.OPEN_LOOPS);


Which calls this...

private File getDataFile(Datafile datafile) {
    File file = null;

    String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    file = new File(baseDir + "/" + datafile.filepath());

    return file;
}


Points for a better name for the enum and good advice regarding who responsibility for the getFileData method (currently all this code is in an Activity) really lies (a new class).

Solution

Enum are a good way to do this in my opinion if this is really static.

Might I suggest you do:

public enum Datafile {
    ACTIVITIES("activities.yaml"),
    OPEN_LOOPS("open_loops.yaml");

private String filepath;

private Datafile(String filepath) {
    this.filepath = filepath;
}

public String getFilepath() {
    return filepath;
}


This is a bit more readable than the overriden methods in each declaration, especially with long enums.

If the values of the filepaths are subject to changes from time to time. I suggest using a properties file. These can be reloaded without recompiling you package, meaning non-developers could maintain them. That is useful in some team setups.

EDIT:
For properties, I suggest you read the java properties tutorial: http://download.oracle.com/javase/tutorial/essential/environment/properties.html. There are also a lot of already well written tutorials about them and I could never hope to match their quality here. Also, never having worked on Android, I do not know if google has provided something that is more user friendly.

For small applications, I would go for enums personally, as they are very easy to manage and usually do the job pretty well.

Code Snippets

public enum Datafile {
    ACTIVITIES("activities.yaml"),
    OPEN_LOOPS("open_loops.yaml");

private String filepath;

private Datafile(String filepath) {
    this.filepath = filepath;
}

public String getFilepath() {
    return filepath;
}

Context

StackExchange Code Review Q#5118, answer score: 14

Revisions (0)

No revisions yet.