Pawan
Pawan

Reputation: 32321

Can I avoid multiple if-else statements in this case?

What is the better way to handle this piece of code

I have a method as shown below , which will accept a parameter i String and returns a int value

below code works fine .

public static int getLoggerLevel(String level)
 {
        int loglevel = 3;
        if (level.equals("INFO")) {
            loglevel = 3;
        }
        else if (level.equals("ERROR")) {
            loglevel = 4;
        } else if (level.equals("FATAL")) {
            loglevel = 5;
        }

        return loglevel;

}

I thought of putting the Key Values in Map , and retrieve that based on the String , but dont want to create an Map i guess which will consume memory

Upvotes: 2

Views: 165

Answers (3)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276266

Assuming Java 7:

public static int getLoggerLevel(String level)
{
        switch(level){
            case "ERROR": return 4;
            case "FATAL": return 5;
            case "INFO": 
            default: return 3;
        }
}

On a more general note, you should probably use an enum instead of a string for this sort of thing. It's a perfect fit. Moreover, it will also work in Java 6.


Here is an alternative solution using enums:

public enum SeverityLevel {
    ERROR, FATAL, INFO
}

 public static int getLoggerLevel(SeverityLevel level)
 {
     switch(level){
          case ERROR: return 4; 
          case FATAL: return 5; 
          case INFO: 
          default: return 3;
     }
 }

No quotes around them, they are enum values, this approach also mitigates bugs caused by typing errors. The big bonus is conceptual though, getLoggerLevel now accepts a SeverityLevel and not a string.

Upvotes: 8

sunil berman
sunil berman

Reputation: 91

Use Switch- case simple to read and understand.

public static int getLoggerLevel(String level)
{
    switch(level){
        case "ERROR": return 4;
        case "FATAL": return 5;
        case "INFO": 
        default: return 3;
    }
}

Also, in your code , you can avoid 1st if block. And once you found correct match.. use return there which will avoid checking further code. which will make your code as below

public static int getLoggerLevel(String level)
{
    int loglevel = 3;
    if (level.equals("ERROR")) {
        return 4;
    } else if (level.equals("FATAL")) {
        return 5;
    }
    return loglevel;

}

Upvotes: 0

DaveH
DaveH

Reputation: 7335

A map would work and would hardly consume any memory, especially if scoped appropriately so that it was just created once.

Upvotes: 0

Related Questions