Home > OS >  Remove multiple Conditions joined by OR from IF-statement
Remove multiple Conditions joined by OR from IF-statement

Time:07-31

I want to remove multiple conditions from the if statement.

How can I achieve that?

I think switch is not what I'm looking for. I'm thinking of something that respect the Open close principal or using an interface to call the different boolean method.

Now 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(User user);
   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:

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<UserRole> combinedPredicate = combineWithOr(
    UserRole::isAdmin,
    UserRole::isWebMaster,
    UserRole::isAdministrateurLiferay,
    UserRole::estResponsableCommercial
);
public static boolean hasMatchingRole(Collection<UserRole> roles,
                                      Predicate<UserRole> predicate){
    
    return roles.stream().anyMatch(predicate);
}

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)

  • Related