Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimizing if-else /switch-case with string options

Tags:

java

What modification would bring to this piece of code? In the last lines, should I use more if-else structures, instead of "if-if-if"

if (action.equals("opt1"))
{
    //something
}
else
{
    if (action.equals("opt2"))
    {
        //something
    }
    else
    {
        if ((action.equals("opt3")) || (action.equals("opt4")))
        {
            //something
        }
        if (action.equals("opt5"))
        {
            //something
        }
        if (action.equals("opt6"))
        {
            //something
        }
    }
}

Later Edit: This is Java. I don't think that switch-case structure will work with Strings.

Later Edit 2:

A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Classes and Inheritance) and a few special classes that "wrap" certain primitive types: Character, Byte, Short, and Integer (discussed in Simple Data Objects ).

like image 765
cc. Avatar asked Nov 27 '22 15:11

cc.


1 Answers

Even if you don't use a switch statement, yes, use else if to avoid useless comparison: if the first if is taken, you don't want all others ifs to be evaluated here since they'll always be false. Also you don't need indenting each if making the last block being so indented that you can't see it without scrolling, the following code is perfectly readable:

if (action.equals("opt1")) {
}
else if (action.equals("opt2")) {
}
else if (action.equals("opt3")) {
}
else {
}
like image 54
Julien Lebosquain Avatar answered Dec 14 '22 22:12

Julien Lebosquain