Refactor multiple If' statements in Java-8

前端 未结 7 1322
轮回少年
轮回少年 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

    As easy refactoring you could introduce two helper methods :

    private String createErrorMsgIfObjectNull(Object o, String errorMessage) {
        return Objects.isNull(o) ?  errorMessage : "";
    }
    
    private String createErrorMsgIfStringEmpty(String s, String errorMessage) {
        return StringUtils.isEmpty(s) ?  errorMessage : "";
    }
    

    And use them in this way :

    StringBuilder mandatoryExcessFields = new StringBuilder(MANDATORY_EXCESS_FIELDS.length);
    
    mandatoryExcessFields.append(createErrorMsgIfObjectNull(excess.getAsOfDate(), MANDATORY_EXCESS_FIELDS[0]))
                         .append(createErrorMsgIfStringEmpty(excess.getStatus(), MANDATORY_EXCESS_FIELDS[1]))
                         .append(createErrorMsgIfObjectNull(excess.getLimit(), MANDATORY_EXCESS_FIELDS[2]))
                         // ...  
    

    By checking the type of the object to test you could still go further. You would have a single helper method that will apply the processing according to the argument type :

    private String createErrorMsgIfNullOrEmptyString(Object o, String errorMessage) {
        if (o instanceof String) {
            return StringUtils.isEmpty((String)o) ? errorMessage : "";
        }
        return Objects.isNull(o) ? errorMessage : "";
    }
    

    A Java 8 stream way would inline the helper in a filter and map() operations and would collect the String result :

    List> objectAndErrorMessageList = new ArrayList<>();
    int i = 0;
    objectAndErrorMessageList.add(new SimpleImmutableEntry<>(excess.getAsOfDate(), MANDATORY_EXCESS_FIELDS[i++]));
    objectAndErrorMessageList.add(new SimpleImmutableEntry<>(excess.getStatus(), MANDATORY_EXCESS_FIELDS[i++]));
    // and so for
    
    String globalErrorMsg = 
        objectAndErrorMessageList.stream()
                                 .filter(e -> {
                                     Object objectToValid = e.getKey();
                                     if (objectToValid == null) {
                                         return true;
                                     }
                                     if (objectToValid instanceof String && StringUtils.isEmpty(objectToValid)) {
                                         return true;
                                     }
                                     return false;
                                 })
                                 .map(SimpleImmutableEntry::getValue)
                                 .collect(Collectors.joining(""));
    

提交回复
热议问题