Home > OS >  Remove multiple boolean OR in a if statement
Remove multiple boolean OR in a if statement

Time:07-27

i want to remove multiple boolean or statement in a if condition, someone knows which is the best practice for that. the switch is not what i'm looking for, i'm looking for something that respect the Open close principal or using an interface to call the differente boolean method that i'm using

 if (utilisateur.isAdmin() || utilisateur.isWebMaster() || utilisateur.isAdministrateurLiferay() || utilisateur.estResponsableCommercial()) {

example of a method :

    public boolean estResponsableCommercial(){
    return roles.stream().anyMatch(Role::isResponsableCommercial);
}

CodePudding user response:

you can try with an Enum:

public enum Role {
   public abstract boolean check();
   ADMIN {
      public boolean check(User user) {
         return user.isAdmin();
      }
   },
   WEBMASTER {
      public boolean check(User user) {
         return user.isWebMaster();
      }
   };
   
   public boolean checkRoles(User user) {
       for(Role role : Role.values()) {
           if(role.check(user)) {
               return true;
           }
       }
       return false;
   }
}

CodePudding user response:

    private static boolean isEstResponsableCommercial(List<String> roles, String roleYouLookingFor) {
    return roles.stream().anyMatch(r->r.equals(roleYouLookingFor));
    }

Signature of anyMatch is: boolean anyMatch(Predicate<? super T> predicate)

CodePudding user response:

It seems like you're looking for a way to combine predicates in order to use them in operations like anyMatch.

If so, you can achieve this using static method Predicate.or():

@SafeVarargs
public static <T> Predicate<T> combineWithOr(Predicate<T>... predicates) {
    
    return Arrays.stream(predicates).reduce(t -> true, Predicate::or); // if `predicates` is empty then method would return `true`, another way of expressing this: `reduce(Predicate::or).orElse(t -> true)`
}

And that how you can apply it to obtain a composite predicate:

Predicate<MyClass> combinedPredicate = combineWithOr(
    MyClass::isAdmin,
    MyClass::isWebMaster,
    MyClass::isAdministrateurLiferay,
    MyClass::estResponsableCommercial
);
public static boolean hasMatchingRole(Collection<UserRole> roles,
                                      Predicate<UserRole> predicate){
    
    return roles.stream().anyMatch(predicate);
}
  •  Tags:  
  • java
  • Related