首页 > 解决方案 > 是创建一个仅用于 Optional.ifPresentOrElse 的类变量是要避免的做法吗?

问题描述

简而言之,我的上下文是:调用一个 API,如果我找到某个标头变量,我会对其进行 subString 以返回一个值。如果不是,我必须返回 Response.status。我已经用这段代码成功地达到了这样的要求:

...
import com.mashape.unirest.*
...
@Controller
public class MainController {
    private final String gmailKey = "XXX";

    private String stringRetorno = "0";

    @ResponseBody
    @GetMapping("/getsessionkey")
    public String getSessionKey() {

        try {

            HttpResponse<String> response = Unirest
                    .post("https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/pricing/v1.0")
                    .header("x-rapidapi-host", "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com")
                    .header("x-rapidapi-key", gmailKey).header("Content-Type", "application/x-www-form-urlencoded")

                    .body("inboundDate=2019-11-25&cabinClass=economy&children=0&infants=0&Country=BR&Currency=BRL&locale=pt-BR&originPlace=GRU-sky&destinationPlace=MCZ-sky&outboundDate=2019-11-19&adults=2")
                    .asString();

            Optional<String> optionalLocation = Optional.ofNullable(response.getHeaders().getFirst("Location"));

            optionalLocation.ifPresentOrElse(l -> stringRetorno = l.substring(l.lastIndexOf("/") + 1),
                    () -> stringRetorno = String.valueOf(response.getStatus()));

        } catch (Exception e) {
            e.printStackTrace();
        }

        return stringRetorno;

    }

我的怀疑取决于我编码它的正确程度。我没有编写 if&null 链,而是决定使用 Optional 的更优雅、更易读的方式。但是,如果我在方法内部创建 stringRetorno,我将面临“在封闭范围中定义的局部变量 stringRetorno 必须是最终的或有效的最终”。

搜索我发现作为解决方案创建 stringRetorno 作为类变量。

所以我的直截了当的问题是:我是否在做一些要避免的事情?一些可能无法回答我的问题但非常有用的问题是:

*** 解决方案

感谢提供的答案

@ResponseBody
@GetMapping("/getsessionkey")
public String getSessionKey() {

    Optional<String> optionalLocation = null;
    HttpResponse<String> response = null;
    try {

        response = Unirest
                .post("https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/pricing/v1.0")
                .header("x-rapidapi-host", "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com")
                .header("x-rapidapi-key", gmailKey).header("Content-Type", "application/x-www-form-urlencoded")

                .body("inboundDate=2019-11-25&cabinClass=economy&children=0&infants=0&Country=BR&Currency=BRL&locale=pt-BR&originPlace=GRU-sky&destinationPlace=MCZ-sky&outboundDate=2019-11-19&adults=2")
                .asString();

        optionalLocation = Optional.ofNullable(response.getHeaders().getFirst("Location"));

    } catch (Exception e) {
        e.printStackTrace();
    }

    return optionalLocation.map(l -> l.substring(l.lastIndexOf("/") + 1))
            .orElse(String.valueOf(response.getStatus()));

}

标签: javahttpapache-httpclient-4.xokhttp3unirest

解决方案


ifPresentOrElse可能不是您要使用的方法,而是.orElse.

return optionalLocation.orElse(String.valueOf(response.getStatus()));

ifPresentOrElse当可选项为空时,如果您要执行某些操作(例如日志记录),您会想要使用。


推荐阅读