Reputation: 1085
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)
?
Upvotes: 1
Views: 115
Reputation: 62864
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;
Upvotes: 6