0

given the following code and alternatives, which would be better from a maintainability and efficiency standpoint. I have existing code and 2 alternatives. After a lot of internet scouring, I haven't found any real answer.

Existing pseudo-java:

Object obj = new ValidObject();
if (TextUtils.equals(obj.method(), CONSTANTS.option1){
} else if (TextUtils.equals(obj.method(), CONSTANTS.option2){
} else if (TextUtils.equals(obj.method(), CONSTANTS.option3){
} else if (TextUtils.equals(obj.method(), CONSTANTS.option4){
} else if (TextUtils.equals(compareString , CONSTANTS.option5) || TextUtils.equals(compareString , CONSTANTS.option6) ){
}

Alternative 1(replace repeated obj.method() with a local variable):
The premise here would be that repeating a function call is wasteful for the CPU, at the cost of storing a String

Object obj = new ValidObject();
String compareString = obj.method();
if (TextUtils.equals(compareString , CONSTANTS.option1){
} else if (TextUtils.equals(compareString , CONSTANTS.option2){
} else if (TextUtils.equals(compareString , CONSTANTS.option3){
} else if (TextUtils.equals(compareString , CONSTANTS.option4){
} else if (TextUtils.equals(compareString , CONSTANTS.option5) || TextUtils.equals(compareString , CONSTANTS.option6) ){
}

Alternative 2(replace if with switch, however, lose TextUtils.equals):
Mainly for readability, but lookup-switch could apparently be faster than if

switch(obj.method()){
    case CONSTANTS.option1:break;
    case CONSTANTS.option2:break;
    case CONSTANTS.option3:break;
    case CONSTANTS.option4:break;
    case CONSTANTS.option5:
    case CONSTANTS.option6:break;
}

What would the best option of these be, is there another one I haven't thought about?

PS:
Obviously, I have omitted code, as any other code wouldn't be relevant. I do not have an if-statement with 5 empty bodies in my code..

ColdFire
  • 6,764
  • 6
  • 35
  • 51
ShadowFlame
  • 2,996
  • 5
  • 26
  • 40

0 Answers0