Let's say we have a function like this:
public String getFullType(String type) {
String result = "";
if (type.startsWith("INT")) result = "integer";
if (type.startsWith("STR")) result = "string";
if (type.startsWith("DBL")) result = "double";
// some code
return result;
}
How can I refactor this triple if statement except for using switch? What would be the 'best' way to do this?
CodePudding user response:
You can use switch as follow:
public String getFullType(String type) {
// Check if type is enough long to not have an ArrayIndexOutOfBoundException
switch(type.substr(0, 3)) {
case "INT": return "integer";
case "STR": return "string";
case "DBL": return "double";
}
return "not found";
}
CodePudding user response:
To me, this looks like a case where you are mapping a discrete set of values to new values. That could be done with a Map
. Like,
private static final Map<String, String> typeMap = new HashMap<>();
static {
typeMap.put("INT", "integer");
typeMap.put("STR", "string");
typeMap.put("DBL", "double");
}
public String getFullType(String type) {
return typeMap.getOrDefault(type.substring(0, 3), "unknown");
}
CodePudding user response:
Here's a solution using enums.
First, a definition of the various enum values:
enum TypeEnum {
INT("integer"),
STR("string"),
DBL("double");
private final String name;
TypeEnum(String name) {
this.name = name;
}
}
Then a new version of getFullType()
:
public static String getFullType(String type) {
return TypeEnum.valueOf(type).name;
}
Here's an example of usage output:
System.out.println(getFullType("INT"));
System.out.println(getFullType("STR"));
System.out.println(getFullType("DBL"));
integer
string
double
As posted above, the code will throw an exception if you ask for something that isn't in the enum, such as: getFullType("abc")
. You could do a number of things to handle that, here's one as an example, showing a
try/catch added to the getFullType()
method:
public static String getFullType(String type) {
try {
return TypeEnum.valueOf(type).name;
} catch (IllegalArgumentException e) {
return "not found";
}
}
Then it runs fine with unexpected input:
System.out.println(getFullType("abc"))
not found