I cannot use String with switch ?

We cannot use String with switch in Java.
For example, this code doesn’t compile :

switch("add") {
    // some cases
}

It may be embarrassing because sometimes we want to check String values with some cases, but if/else chains look rather ugly.
How would you write a more sexy implementation ?
Two ways are possible : the first is to convert String in enum instance, and use it in switch; the second is to remove the switch using Map.

Use enum instance
First, create enum who represents all cases :

enum Operation {
    ADD, SUB, MUL, DIV;

    static public Operation get(String str) {
        if(str != null)
            try {
                return valueOf(str.toUpperCase());
            } catch (IllegalArgumentException e) {
                throw new RuntimeException(str + " operation is unknown", e);
            }
        else
            throw new IllegalArgumentException("parameter cannot be null");
    }
}

Now you can simply use switch with the Operation enum :

int a = 4;
int b = 2;
switch(Operation.get("add")) {
    case ADD:
        System.out.println(a + b);
        break;
    // others cases
}

Use Map
I think this is the more elegant implementation because it allows a better flexibility.
To remove switch, you can define interfaces which represent treatments and create some implementations of these interfaces. Then you’ll create a map which uses the string as the key, and the Process as the value.

For example, consider the following Process interface and one of the implementation :

interface Process {
    float proceed(int a1, int a2);
}

class Add implements Process {
    public float proceed(int a1, int a2) {
        return a1 + a2;
    }
}

// implement others processes

Now, just fill the Map, and get the correct process instead of using the switch.


// you can declare it as instance variable
Map<String, Process> process = new HashMap<String, Process>();
// you can fill it in constructor or init block.
process.put("add", new Add());
process.put("sub", new Sub());
process.put("mul", new Mul());
process.put("div", new Div());

System.out.println(
    (int) new Main().process.get("add").proceed(4, 2)
    );

Good bye switch !

Advertisements

One thought on “I cannot use String with switch ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s