Reputation: 17883
I have written a method. I want to return the employee type based on class.
I am thinking if there is any better and standard implementation here.
public static EmployeeType decideEmployeeType(String className)
{
if(className.equalsIgnoreCase("A") || className.equalsIgnoreCase("1"))
{
return EmployeeType.ADMIN;
}
else if(className.equalsIgnoreCase("S") || className.equalsIgnoreCase("2"))
{
return EmployeeType.SERVICE;
}
else
{
//throw exception
}
}
Can some one suggest, better approach.
Upvotes: 0
Views: 75
Reputation: 791
I can give a code example which is easily extendible by changing a constant without hampering the business logic:
private static HashMap<String, EmployeeType> employeeTypeTranslations = new HashMap<String,EmployeeType> () {{
put("a",EmployeeType.ADMIN);
put("s",EmployeeType.SERVICE);
put("1",EmployeeType.ADMIN);
put("2",EmployeeType.SERVICE);
}};
public static EmployeeType decideEmployeeType(String class) {
employeeTypeTranslations.get(class.toLowerCase());
}
What this allows is that you can in future may be externalize this map to a properties file or an XML or whatever.
Upvotes: 5
Reputation: 8106
If you are using JDK 7 you can use switch with strings.
switch(className){
case "A": /* do your stuff */
break;
default:
//do default stuff
}
Im not sure why you having class 1 OR A (i guess it's because of ProGuard or any other obfuscator?
If yes, use a Constant. Class a = YourClass.getClass();
The Obfuscator will change it automatically.
Upvotes: 1
Reputation: 2247
There is no better way, but you can use 'valueOf' if you are using enum.
EmployeeType.valueOf("ADMIN") // return EmployeeType.ADMIN
NOTE: case sensitive
Upvotes: 1