Reducing if-else statements in Java

I have the following code:

void f(String t)
{
  if(t.equals("a"))
  {
    someObject.setType(ObjectType.TYPE_A);
  }
 else if(t.equals("b"))
  {
    someObject.setType(ObjectType.TYPE_B);
  }

// 50 more similar code

}

Is there any simple way to rewrite the if-else condition so as not to have that much code?

Answers


You should use something to eliminate the repetition of someObject.setType(ObjectType....)) If ObjectType is an enum, then write a method there similar to valueOf that will achieve that. See if you like this kind of solution:

void f(String t) { someObject.setType(ObjectType.byName(t)); }

enum ObjectType {
  TYPE_A, TYPE_B;
  public static ObjectType byName(String name) {
    return valueOf("TYPE_" + name.toUpperCase());
  }
}

Use a Map (which you'll have to populate) that maps from String to whatever type your ObjectType.TYPE_x values are.


I would add this as a functionality of the enum:

public enum ObjectType {
    TYPE_A("a"),
    TYPE_B("b");

    private String stringType;

    private ObjectType(String stringType) {
        this.stringType = stringType;
    }

    public String getStringType() {
        return this.stringType;
    }

    public static ObjectType fromStringType(String s) {
        for (ObjectType type : ObjectType.values()) {
            if (type.stringType.equals(s)) {
                return type;
            }
        }
        throw new IllegalArgumentException("No ObjectType with stringType " + s);
    }
}

...

void f(String t) {
    someObject.setType(ObjectType.fromStringType(t));
}

If you can refactor t into a char, you could use switch instead (Java 6):

void f(char t) {

  switch(t) {

    case 'a`:
      someObject.setType(ObjectType.TYPE_A);
      break;
    case 'b':
      someObject.setType(ObjectType.TYPE_B);
      break;

    // ...

  }

}

As Marko pointed out, you could go with String too in Java 7.

It isn't that much shorter, but more elegant. Moreover, I think it might be faster too, as switch works close to O(1) with jump tables (Can somebody confirm whether this is true?), whether a number of if statements is O(n).

Fore more complex implementations than just a single setType you might think of a State Pattern implementation too.


1.You can go for Switch statement if you have number of if conditions more than 3.

2.you can convert your if else statements to ternary operations


The other suggestions are great - particularly smarter enums and maps. But the first most basic refactoring I would tackle here is to extract a method to return the enum directly and have the caller perform nothing more than the setType to that method's return value.

void f(String t) {
  final ObjectType type = findType(t);
  if (type != null)
    someObject.setType(type);
  }

ObjectType findType(String t) {
  if (t.equals("a")) return ObjectType.TYPE_A;
  if (t.equals("b")) return ObjectType.TYPE_B;
  // 50 more similar code
  }

In some cases this will be sufficient in and of itself; in others the findType() method may lead you to a simple map- or enum-based solution.


Need Your Help

push database to rooted device

android database insert push

I'm trying to access the data/ folder on my device I cant get it to open?..I've rooted my phone and I want to push my database to the database folder on my device so that I can run my developed ap...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.