Refactor multiple If' statements in Java-8

前端 未结 7 1321
轮回少年
轮回少年 2021-01-06 20:05

I need to validate mandatory fields in my class

For example, 9 fields must not be null.

I need to check if they are all null but I

相关标签:
7条回答
  • 2021-01-06 20:58

    A little bit complicated, but I have a good solution because it's generic and can be used with any objects:

    Excess excess = new Excess(new Limit());
    
    Checker<Excess, Excess> checker = new Checker<>(
        identity(),
        List.of(
            new CheckerValue<>("excess date is null", Excess::getAsOfDate),
            new CheckerValue<>("limit is null", Excess::getLimit)
        ),
        List.of(new Checker<>(Excess::getLimit, List.of(new CheckerValue<>("limit id is null", Limit::getId))))
    );
    
    System.out.println(checker.validate(excess));
    

    This code will print:

    excess date is null
        limit id is null
    

    The first class Checker contains:

    • sourceFunction - for getting the object
    • values - for checking each field from object obtained from sourceFunction
    • children - a list of Checker

      class Checker<S, T> {
      
      Function<S, T> sourceFunction;
      List<CheckerValue<T>> values;
      List<Checker<T, ?>> children = emptyList();
      
      /*All args constructor; 2 args constructor*/
      
      public String validate(S object) {
          T value = sourceFunction.apply(object);
          if(value != null) {
              String valueString = values.stream().map(v -> v.validate(value)).filter(Optional::isPresent).map(Optional::get).collect(joining("\n"));
              valueString += "\n\t";
              valueString += children.stream().map(c -> c.validate(value)).collect(Collectors.joining("\n"));
              return valueString;
          }
          return "";
      }
      }
      

    and CheckerValue class:

    class CheckerValue<T> {
    
        String validationString;
        Function<T, Object> fun;
    
        /*all args constructor*/
    
        public Optional<String> validate(T object) {
            return fun.apply(object) != null ? Optional.empty() : Optional.of(validationString);
        }
     }
    
    0 讨论(0)
提交回复
热议问题