justanotherguy
justanotherguy

Reputation: 405

Simplify a switch statement to avoid code duplication

I have the following code:

String fullName = "";
switch(name) {
  case "name1":
    fullName = String.format("%s %s", name, "surname1");
    break;

  case "name2":
    fullName = String.format("%s %s", name, "surname2");    
    break;

  case "name3":
    fullName = String.format("%s %s", name, "surname3");
    break;
  ...
}

(there's a break statement after the cases, I just haven't written it here)

So here's the problem:

There's 16 different case statements all having the exact same code, except for the argument to String.format().

Is there any way I can simplify this code?


Note: Java 8 is a must

Upvotes: 0

Views: 355

Answers (2)

Brian Goetz
Brian Goetz

Reputation: 95534

The Map approach outlined elsewhere is probably your best best for Java 8, but note that as of Java 14, you can use a switch expression:

String surname = switch (name) { 
    case "name1" -> "surname1";
    case "name2" -> "surname2";
    ...
};
String fullName = String.format("%s %s", name, surname);
 

Upvotes: 5

MC Emperor
MC Emperor

Reputation: 23047

Well, if all of your cases have that exact form, then you could simply do something like this:

String surname;
switch (name) {
    case "name1":
        surname = "surname1";
        break;
    case "name2":
        surname = "surname2";
        break;
    default:
        surname = "";
        break;
}
String fullname = String.format("%s %s", name, surname);

Or use a Map to look up the value:

Map<String, String> mapping = new HashMap<>();
mapping.put("name1", "surname1");
mapping.put("name2", "surname2");
mapping.put("name3", "surname3");

String surname = mapping.get(name); // Assuming name is always a valid map entry
String fullname = String.format("%s %s", name, surname);

Upvotes: 5

Related Questions