Reputation: 39
I am wondering if there is any design pattern for such situation:
private static boolean check(String s) {
if(isBook(s)) {
System.out.println("Book");
return false;
}else if(isEmail(s)) {
System.out.println("Email");
return false;
}
return true;
}
private static boolean isBook(String s) {
if(s.equals("B")) return true;
return false;
}
private static boolean isEmail(String s) {
if(s.equals("E")) return true;
if(s.length() > 4) return true;
return false;
}
There will be many isXXX in check method, but I don't wanna to have many if-else statement.
Upvotes: 0
Views: 1224
Reputation: 4091
Since you have many isXXX checks, I would make the system more generic in order to avoid a huge switch (or if/else)
private static boolean check(String s, Collection<Predicate<String>> rules)
{
return rules.stream()
.noneMatch(rule -> rule.test(s));
}
Declare your rules as follow
Predicate<String> isBook = s -> s.equals("B");
Predicate<String> isEmail = s -> s.equals("E") || s.length() > 4;
Usage
check("E", Arrays.asList(isBook, isEmail)); //false
check("B", Arrays.asList(isBook, isEmail)); //false
check("Emo", Arrays.asList(isBook, isEmail)); //true
check("Email", Arrays.asList(isBook, isEmail)); //false
Upvotes: 1
Reputation: 1637
Instead of creating an is... method for each possible type, introduce an enumeration and make one method that returns the type.
This way you can easily use a switch statement.
Upvotes: 1