javaif-statement

What is the best way to refactor an if else branch


I have an if-else branching like

if(name.contains(substring)){
    if(name.contains(substring1)){
        return "this";
    }else if(name.contains(substring2)){
        return "that";
    }
    ...
}else if(){
     // if else ladder
}
....//else if ladder continues
else{
    return "them"
}

What is the best way to refactor this? That what is the most efficient way to make logic like this?


Solution

  • Excessive if/else or switch statements may indicate poor design.

    In some situations it could be better to use interfaces (polymorphism), see for example Replace Conditional with Polymorphism.

    Certainly not all ifs are unnecessary. But it's good to avoid mixing control structures with doing work as much as possible. In the end, code should be easily readable.