Refactor multiple If' statements in Java-8

前端 未结 7 1376
轮回少年
轮回少年 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 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 {
      
      Function sourceFunction;
      List> values;
      List> 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 {
    
        String validationString;
        Function fun;
    
        /*all args constructor*/
    
        public Optional validate(T object) {
            return fun.apply(object) != null ? Optional.empty() : Optional.of(validationString);
        }
     }
    

提交回复
热议问题