Refactor multiple If' statements in Java-8

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

    All the Object.isNull might be replaced with Optional object and its methods. Let's take example the line:

    if (!Objects.isNull(excess.getLimit()) && Objects.isNull(excess.getLimit().getId())) {
        mandatoryExcessFields.append(MANDATORY_EXCESS_FIELDS[3]);
    }
    

    Would be simplified to (and squeezed on 1 line remains readable):

    Optional.ofNullable(excess.getLimit())                                // check the Limit
            .map(limit -> limit.getId())                                  // if not null, getId
            .ifPresent(i -> builder.append(MANDATORY_EXCESS_FIELDS[3]));  // Append if present
    

    And for the String.isEmpty(s) check, you have to create Optional in this way:

    Optional.ofNullable(excess.getStatus()).filter(s -> !StringUtils.isEmpty(s))
    

    A short way would be to pass those Optional object into the map and use the index to iterate through them and perform an action. int count is a number of checkings:

    Map> map = new HashMap<>();
    map.put(...);
    map.put(1, Optional.ofNullable(excess.getStatus()).filter(s -> !StringUtils.isEmpty(s)));
    map.put(...);
    map.put(3, Optional.ofNullable(excess.getLimit()).map(limit -> limit.getId()));
    map.put(...);
    
    for (int index=0; index mandatoryExcessFields.append(MANDATORY_EXCESS_FIELDS[index]));
    }
    

    And the for-cycle might be simplified as well:

    IntStream.range(0, count).forEach(index -> 
        map.get(index)
           .ifPresent(any -> mandatoryExcessFields.append(MANDATORY_EXCESS_FIELDS[index])));
    

提交回复
热议问题