Home > Mobile >  create an enum to pass values in methods
create an enum to pass values in methods

Time:10-24

I have a small project we use for jenkins pipline the code has written in groovy, I create an enum like below :

the whole purpose is to pass an enum in the functions and get back the type of the file or the file extension so we reuse the code for other file type with out hard coding

enum FileExtension {

CSV, JSON, PROPERTIES;

static String getSrcFile(FileExtension fileExtension) {
    String src_File = "./master.csv";
    switch (fileExtension) {
        case CSV:
            src_File = "./master.csv";
            break;
        case JSON:
            src_File = "./master.json";
            break;
        case PROPERTIES:
            src_File = "./master.properties";

    };
    return src_File;
};

static String getFileFormat(FileExtension fileExtension) {
    String fileFormat = "csv";

    switch (fileExtension) {
        case CSV:
            fileFormat = "csv";
            break;
        case JSON:
            fileFormat = "json";
            break;
        case PROPERTIES:
            fileFormat = "properties";

    };
    return fileFormat;
};

}

I am using it in the following :

public class Hello {
public static void main(String[] ars) {
    FileExtension fileExtension = FileExtension.JSON;
    System.out.println(test(FileExtension.CSV));

}

public static String test(FileExtension fileExtension){

     return fileExtension.getSrcFile(fileExtension);
  }

}

My questions there is a way to avoid pass fileExtension in the test method ? and do you think the code is correct ?

CodePudding user response:

Don't make those methods static, give the enum a property which is the extension:

    enum FileExtension {
        CSV("csv"), JSON("json"), PROPERTIES("properties");
        
        private final String extension;
        
        FileExtension(String extension) {this.extension = extension;}

        public String getSrcFile() {
            return "master."   extension;
        }

        public String getFileFormat() {
            return extension;
        }
    }

CodePudding user response:

enum FileExtension {

    CSV, JSON, PROPERTIES;

    public String getSrcFile() {
        return "./master."   getFileFormat();
    }

    public String getFileFormat() {
      return toString().toLowerCase();
    }
}

To make a test for all enumeration values you can do the following:

for (FileExtension fileExtension : FileExtension.values() ) {
    // do your tests 
}

And if you really want to have good design, don't put the method getSrcFile() with hard-coded name "master" into enum code. Or at least, pass this name as parameter.

  • Related