Reputation: 184
i have a some strings(String result) that user inserted it in app without any case-sensitivity policy user can insert such as : "fail" or "Fail" or "FAIL" and "Success" or "success" and etc . and also i have just one method for each of them like : fail() , success() and must call related method
now i want use a one string into switch-case statement by use below constants(success,fail,...) :
public final class ActionResultStatus
{
public static final String SUCCESS = "Success";
public static final String FAIL = "Fail";
public static final String REJECTED = "Rejected";
public static final String IN_PROGRESS = "InProgress";
}
String result = userClass.getResult(); //UserClass is a container class for user inputted data
switch(result)
{
case ActionResultStatus.FAIL:
fail();
case ActionResultStatus.SUCCESS :
success();
}
Note that's :
1-i dont want use toUpperCase()
or toLowerCase()
for result because i must add more case statements .
2-i cant change my Constatn class field value to lowerCase they must be pascal-case like:"Success" because they must will be persist on DB exactly in pascal-case mode
3-and i think i couldn't use equalIgnoreCase()
method for this situation because this isn't if-statement .
Thnak You.
Upvotes: 0
Views: 276
Reputation: 1760
Separate the logic out a bit. First turn your statuses into and Enum that has a lookup function to find the enum:
public enum ActionResultStatus {
SUCCESS("Success"),
FAIL("Fail"),
REJECTED("Rejected"),
IN_PROGESS("InProgress"),
UNKNOWN("Unknown");
private String outputStr;
private ActionResultStatus(String output) {
outputStr = output;
}
public static ActionResultStatus findStatus(String input) {
for (ActionResultStatus status : values()) {
if (input.equalsIgnoreCase(status.outputStr)) {
return status;
}
}
return UNKNOWN;
}
public String toString() {
return outputStr;
}
}
Then your processing logic become something like:
ActionResultStatus status = ActionResultStatus.findStatus(userClass.getResult());
switch (status) {
case FAIL: fail(); break;
case SUCCESS: success(); break;
default: break;
}
Upvotes: 3