java - 是创建一个仅用于 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 作为类变量。
所以我的直截了当的问题是:我是否在做一些要避免的事情?一些可能无法回答我的问题但非常有用的问题是:
我是否应该更喜欢其他 Java HTTP 客户端而不是 com.mashape.unirest 可能已经提供了 Optional 以便我能够编写更少冗长的代码?我根本不想比较图书馆。我的重点是与接收缺少特定键(位置)的响应标头的可能性相结合。如果 API Provider 建议的轻量级 unirest 迫使我采取变通办法,那么建议另一个提供 Optional 作为答案的库可能会对我有所帮助。
在 Try/Catch 块内写 Optional 不是压倒性的吗?
*** 解决方案
感谢提供的答案
@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()));
}
解决方案
ifPresentOrElse
可能不是您要使用的方法,而是.orElse
.
return optionalLocation.orElse(String.valueOf(response.getStatus()));
ifPresentOrElse
当可选项为空时,如果您要执行某些操作(例如日志记录),您会想要使用。
推荐阅读
- flutter - Flutter await 在继续之前不等待
- regex - 通过使用生成文件的循环删除空格并替换文件名中的非 ASCII 字符
- python - Kinesis Firehose 在多个区域中的相同流
- excel - Excel 搜索 - 多个结果
- ruby-on-rails - 如何与 Spree::User 建立关系?
- python - python如何在模块路径和成员函数之间消除歧义
- python - 具有不同标准差和每行平均值的 Numpy 数组
- ios - 首次触摸后隐藏和取消隐藏 UIButton
- python - 带有 MS Edge 浏览器的 Python (Selenium):“连接中止。”、ConnectionResetError(10054, ...)“Microsoft Web 驱动程序已停止工作”
- flask - WTForm Submit 上的引导模式关闭 - 不显示错误 - Flask