0

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.

mi_mo
  • 135
  • 1
  • 8
  • 4
    Very difficult to find a solution with all those constraints, why don't you use a `if-statement` instead of a `switch` ? – Yassin Hajaj Apr 05 '21 at 13:19
  • `String result = userClass.getResult().toUpperCase();` – Med Elgarnaoui Apr 05 '21 at 13:34
  • @user15358848 You're right and I got aware soon enough. But just removing the characters obviously didn't delete the comment. But now it seems to have gone. – Jörg Apr 05 '21 at 15:18
  • @yassin-hajaj i dont want use if because i very heard if-statement reduce performance , exactly when you use if more . is it true? – mi_mo Apr 06 '21 at 08:25

1 Answers1

3

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;
}
Ryan
  • 1,762
  • 6
  • 11