在这里使用lambda,function和optional有什么好处?

时间:2019-04-24 16:08:44

标签: java lambda functional-programming

今天,我看到了以下代码片段,该片段使用Java中的lambda,可选参数和函数来呈现特定的端点响应。 此功能,lambda和该可选功能的使用是否确实需要并在此处证明合理性?有什么好处?

@RequestMapping(value = "/api/v1/User", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public String getBySomeAttribute(@RequestParam(value = "someAttribute", required = true) String someAttribute,
                                 HttpServletResponse response) {
    User user = service.getBySomeAttribute(someAttribute);
    return createResponse(user, response);
}

private String createResponse(User user, HttpServletResponse response) {
    String responseBody = maybe((User u) -> {
        response.setStatus(SC_OK);
        return toJsonString(userJsonMapper.jsonMapFrom(u));
    }).apply(user).orElse("");

    setResponseHeaders(response, responseBody.length());
    return responseBody;
}

private Function<User, Optional<String>> maybe(Function<User, String> f) {
    return (u) -> {
        String s = null;
        if (u != null && u.getEnabled()) {
            s = f.apply(u);
        }
        return s != null ? of(s) : Optional.empty();
    };
}

private void setResponseHeaders(HttpServletResponse response, int responseBodySize) {
    response.setHeader("Content-Length", valueOf(responseBodySize));
    response.setHeader("Expires", "1");
    response.setHeader("Cache-Control", "no-cache");
}

1 个答案:

答案 0 :(得分:1)

我找不到任何理由去做几乎所有的事情。提供的代码似乎等同于:

@RequestMapping(value = "/api/v1/User", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public String getBySomeAttribute(@RequestParam(value = "someAttribute", required = true) String someAttribute,
                                HttpServletResponse response) {
    User user = service.getBySomeAttribute(someAttribute);
    return createResponse(user, response);
}

private String createResponse(User user, HttpServletResponse response) {
    String responseBody = "";
    if(user != null && user.getEnabled()) {
        String responseBody = toJsonString(userJsonMapper.jsonMapFrom(user))
        response.setStatus(SC_OK);
    }

    setResponseHeaders(response, responseBody.length());
    return responseBody;
}

private void setResponseHeaders(HttpServletResponse response, int responseBodySize) {
    response.setHeader("Content-Length", valueOf(responseBodySize));
    response.setHeader("Expires", "1");
    response.setHeader("Cache-Control", "no-cache");
}

但是(我认为)以上内容非常容易阅读,理解和维护。除非该lambda在其他地方得到广泛使用,否则我看不出它存在的原因。老实说,即使用于其他地方,这也可能是过大的杀伤力。