【问题标题】:Is there a more innovative way to handle null exceptions in the following cases?在以下情况下是否有更创新的方法来处理空异常?
【发布时间】:2021-09-06 14:59:39
【问题描述】:

现在我为 Puppy 创建了一个响应

@Getter
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PUBLIC)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PuppyResponse {

    private Long puppyId;

    private String name;

    private Integer age;

    private String breed;

    private Long vetId;

    private String vetName;

    public PuppyResponse(Long puppyId, String name, Integer age, String breed) {
        this.puppyId = puppyId;
        this.name = name;
        this.age = age;
        this.breed = breed;
    }

    public static PuppyResponse of(Puppy puppy) {
        Optional<Vet> vet = Optional.ofNullable(puppy.getVet());
        if(vet.isPresent()) {
            return new PuppyResponse(
                    puppy.getPuppyId(),
                    puppy.getName(),
                    puppy.getAge(),
                    puppy.getBreed(),
                    vet.get().getVetId(),
                    vet.get().getName()
            );
        }else {
            return new PuppyResponse(
                    puppy.getPuppyId(),
                    puppy.getName(),
                    puppy.getAge(),
                    puppy.getBreed()
            );
        }
    }

    public static List<PuppyResponse> listOf(List<Puppy> puppies) {
        return puppies.stream()
                .map(PuppyResponse::of)
                .collect(Collectors.toList());
    }
}

狗属性 vet 可能为空。 我将 Puppy 设计为根据它是否为空来使用不同的构造函数,但这似乎不是一个好方法。 当然它可以正常工作,但我想以更好的方式设计它。如何处理空值?

【问题讨论】:

    标签: spring oop null optional nullable


    【解决方案1】:

    如果您只想在puppy.getVet() 为空的情况下使用orElseGet 提供新的 Veet 对象

    Vet vet = Optional.ofNullable(puppy.getVet()).orElseGet(Vet::new);
    

    如果你想在puppy.getVet() 为空的情况下提供默认的 Veet 对象

    Vet vet = Optional.ofNullable(puppy.getVet()).orElseGet(PuppyResponse::getDefaultVet);
    

    这样您就不需要检查 ifPresent 并相应地创建响应

    return new PuppyResponse(
        puppy.getPuppyId(),
        puppy.getName(),
        puppy.getAge(),
        puppy.getBreed(),
        vet.getVetId(),
        vet.getName()
    );
    

    提供默认的兽医对象

    private static Vet getDefaultVet(){
        Vet v = new Vet();
        v.setVetId(0);
        v.setName("Default Name");
        return v;
    }
    

    【讨论】:

    • 如果值为null,想留空值怎么办?
    • .orElseGet(Vet::new); 如果puppy.getVet() 为空,这将提供空对象
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 2021-08-18
    • 2011-06-11
    相关资源
    最近更新 更多