Java可选接口:可选对象链上的嵌套条件

时间:2019-03-27 10:44:08

标签: java optional

我想再次将此代码编写为完整的Optional流利方法,以便做到这一点:

Optional<Reference> reference = this.referenceService.get(id);
if (!reference.isPresent()) {
    return Response.status(Status.NOT_FOUND).build();
}

EntityTag entityTag = this.eTag(reference.get());
ResponseBuilder responseBuilder = this.request.evaluatePreconditions(entityTag);

if (Objects.isNull(responseBuilder)) {
    responseBuilder = Response
        .ok()
        .entity(reference.get())
        .cacheControl(this.cacheControl)
        .tag(entityTag);
}

return responseBuilder.build();

到目前为止,我已经能够做到这一点:

return this.referenceService.get(id)
    .map(this::eTag)
    .map(this.request::evaluatePreconditions)
    .orElse(Response.status(Status.NOT_FOUND))
    .cacheControl(this.cacheControl)
    .tag(this.eTag(this.referenceService.get(id).get()))
    .build();

但是此代码与先前的代码不同。

我有两个条件要处理:

if (!reference.isPresent()) {
    return Response.status(Status.NOT_FOUND).build();
}

if (Objects.isNull(responseBuilder)) {

我不太清楚如何解决这个问题。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

第一个条件if (!reference.isPresent()).orElse(Response.status(Status.NOT_FOUND))覆盖

涵盖第二个条件if (Objects.isNull(responseBuilder))  从this.request.evaluatePreconditions(entityTag)的结果中选择Optional,然后从orElseGet返回ok构建器

下面的代码是从我的头顶写的,我没有测试

this.referenceService
    .get(id)
    .map(this::eTag)
    .map(entityTag -> Optional.ofNullable(this.request.evaluatePreconditions(entityTag))
                                .orElseGet(() -> Response.ok()
                                                        .entity(entityTag)
                                                        .cacheControl(this.cacheControl)
                                                        .tag(entityTag)))
    .orElse(Response.status(Status.NOT_FOUND))
    .buld();

为简化表达式,可以在方法中重构Optional.ofNullable(...).orElseGet(...)部分并调用该方法,而不用全部内联

类似以下内容

private ResponseBuilder getBuilderOrDefault(EntityTag entityTag) {
    return Optional.ofNullable(this.request.evaluatePreconditions(entityTag))
                   .orElseGet(() -> Response.ok()
                                            .entity(entityTag)
                                            .cacheControl(this.cacheControl)
                                            .tag(entityTag));
}

映射将变为

this.referenceService
    .get(id)
    .map(this::eTag)
    .map(this::getBuilderOrDefault)
    .orElse(Response.status(Status.NOT_FOUND))
    .buld();
相关问题