Use Java 8 Optional in existing Java 7 code

前端 未结 4 913
傲寒
傲寒 2021-01-06 20:22

I have an assignment in which I need to convert the following pre-Java 8 code to Java 8 code. Below is just one method which is giving me hard time to finish up:

         


        
4条回答
  •  盖世英雄少女心
    2021-01-06 20:51

    You may replace your initial null checks with

    Optional.ofNullable(nameStartsWith)
            .flatMap(x -> Optional.ofNullable(region))
            .flatMap(x -> Optional.ofNullable(loader))
            .orElseThrow(() -> new IllegalArgumentException(
                "The VehicleLoader and both region and nameStartsWith"
              + " are required when loading VehicleMake matches"));
    

    but it’s an abuse of that API. Even worse, it wastes resource for the questionable goal of providing a rather meaningless exception in the error case.

    Compare with

    Objects.requireNonNull(region, "region is null");
    Objects.requireNonNull(nameStartsWith, "nameStartsWith is null");
    Objects.requireNonNull(loader, "loader is null");
    

    which is concise and will throw an exception with a precise message in the error case. It will be a NullPointerException rather than an IllegalArgumentException, but even that’s a change that will lead to a more precise description of the actual problem.

    Regarding the rest of the method, I strongly advice to never let Collections be null in the first place. Then, you don’t have to test the result of getVehicleMakesByRegion for null and won’t return null by yourself.

    However, if you have to stay with the original logic, you may achieve it using

    return Optional.ofNullable(loader.getVehicleMakesByRegion(region.name()))
                   .map(regionMakes -> regionMakes.stream()
                        .filter(make -> Optional.ofNullable(make.getName())
                                                .filter(name->name.startsWith(nameStartsWith))
                                                .isPresent())
                        .collect(Collectors.toList()))
                   .orElse(null);
    

    The initial code, which is intended to reject null references, should not get mixed with the actual operation which is intended to handle null references.

提交回复
热议问题