简体   繁体   中英

How to avoid if-else statements in this scenario

I have a class Grades who has the following body:

public class Grades {

    public static Grade getGrades(int marks) {
        if (marks < 10) {
            return Grade.FAILED;
        } else if (marks < 13) {
            return Grade.DISTINCTION;
        } else if (marks < 15) {
            return Grade.GREAT;
        } else {
            return Grade.GREATEST;
        }
    }

    public static void main(String args[]){
        System.out.println(getGrades(6));
    }
}

And a enum class:

public enum Grade {

    FAILED("F"),
    DISTINCTION("D"),
    GREAT("G"),
    GREATEST("G");


    private String code;

    Grade(String code){
        this.code = code;
    }

    public String getCode() {
        return code;
    }

}

How could I avoid the if else construction when calling getGrades(int marks) ?

I would implement a decision table for this. It will be simply a mapping between a Predicate (a function that takes an input and returns true or false ) and a corresponding result if the Predicate is evaluated to true .

Note that Java8 introduces the Predicate<T> interface, which could be very helpful in your case. In addition, it could be represented as a lambda, which will reduce the verbosity of the code.

So you'd have:

Map<Predicate<Integer>, Grade> table = new LinkedHashMap<Predicate<Integer>, Grade>() {{
      put (x -> x < 10, Grade.FAILED);
      put (x -> x < 13, Grade.DISTINCTION);
      put (x -> x < 15, Grade.GREAT);
}};

Then, just iterating the decision table and to evaluating the Predicate s until finding such that's evaluated to true , should give you the answer:

for (Entry<Predicate<Integer>, Grade> entry : table.entrySet()) {
    if (entry.getKey().test(marks)) {
        return entry.getValue();
    }
}
return Grade.GREATEST;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM