speedRS
speedRS

Reputation: 1240

Constants and simplifying enum value access

For an enum with only one member variable, is there a simpler (and best practices) way to access it without the use of an accessor method? I had alternatively considered using public static final variables in a constants class but the more I read, the more people suggest using enum as the way to encapsulate those values.

To attempt to illustrate what I mean, I've included the following example:

public enum FILE_NAME {

   MAIN("MAIN.TXT"),
   ATTACHMENT("ATTACHMENT.TXT"),
   OTHER("OTHER.HTM");

   private String fileName;

   FILE(String fileName) {
     this.fileName = fileName;
   }

   public String getfileName() {
     return fileName;
   }
}

I would then normally access that value like so:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(bos);

// Add file
zip.putNextEntry(new ZipEntry(FILE_NAME.MAIN.getFileName()));

For my particular use case, I'd much prefer to be access the filename with a call like:

...
zip.putNextEntry(new ZipEntry(FILE_NAME.MAIN));

In doing so, the code reduces the length (and almost syntactic redundancy of calling a filename of a file) of the call needed to access the MAIN file name text. While this may not even be feasible or desirable, I'm curious to know if it's worth considering.

Thanks.

Upvotes: 2

Views: 420

Answers (3)

irreputable
irreputable

Reputation: 45433

You can have aliases

enum Pet
{ 
    cat("meow"), 
    dog("woof") 

    String getSound()
}


public static final Pet CAT = Pet.cat;

public static final String MEOW = Pet.cat.getSound();

Upvotes: 0

Bohemian
Bohemian

Reputation: 424993

To simplify it, and still keep it safe, use a public final String field for the file name:

public enum FileType {
    MAIN("MAIN.TXT"),
    ATTACHMENT("ATTACHMENT.TXT"),
    OTHER("OTHER.HTM");

    // Name in all-caps to make it look like the constant it is
    public final String FILENAME;

    private FileType(String fileName) {
       this.FILENAME = fileName;
    }
}

To use it:

zip.putNextEntry(new ZipEntry(FileType.MAIN.FILENAME));

Note that change of class name to "FileType" to better adhere to java standards.

Upvotes: 2

emory
emory

Reputation: 10891

It seems like the following would work better

public enum FILE_NAME {

   MAIN("MAIN.TXT"),
   ATTACHMENT("ATTACHMENT.TXT"),
   OTHER("MAIN.TXT");

   private String fileName;

   FILE(String fileName) {
     this.fileName = fileName;
   }

   public void putEntry ( ZipOUtputStream zip )
   {
         zip.putNextEntry(new ZipEntry(this.getFileName()));
   }

   public String getfileName() {
     return fileName;
   }
}

Then you could use it like:

FILE_NAME.MAIN.putEntry(zip);

Upvotes: 0

Related Questions