我正在修复旧版模块中的某个问题,并遇到了此代码,这些代码从可返回null的请求对象获取cookie数组。代码查找特定的cookie,如果存在则返回cookie值,否则返回null。下面是现有代码
final Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
final Cookie cookie = cookies[i];
if ("random cookie".equals(cookie.getName())) {
return cookie.getValue();
}
}
return null;
我将其重构为类似的内容
final Cookie[] cookies = request.getCookies();
if (cookies != null) {
Optional<Cookie> cookie = Arrays.stream(cookies).
filter(e -> "random cookie".equals(e.getName())).
findAny();
return cookie.isPresent() ? cookie.get().getValue() : null;
}
return null;
可以更好地重构以上内容吗?
最好使该方法返回Optional<String>
-但如果不能,那么如何处理:
final Cookie[] maybeCookies = request.getCookies();
return Optional.ofNullable(maybeCookies)
.flatMap(cookies -> Arrays.stream(cookies)
//Find the cookie if we can.
.filter(e->"random cookie".equals(cookie.getName()))
.findAny()
)
//If we have a matching cookie, return its value.
.map(e->e.getValue())
//otherwise return null to retain original behaviour
.orElse(null);
我会将其重构为一个返回Optional<String>
的方法:
public Optional<String> getCookieValue(String name) {
final Cookie[] cookies = request.getCookies();
if(cookies == null) return Optional.empty();
return Arrays.stream(cookies)
.filter(e -> name.equals(e.getName()))
.findAny().map(Cookie::getValue);
}
然后,此方法的调用者将根据他们打算如何使用结果来执行任何上述操作:
getCookieValue("random cookie").ifPresent(e -> { ... });
getCookieValue("random cookie").orElse(null);
....
....
返回Optional<String>
以避免处理nullity,并让此方法的用户决定在“无值情况”下该做什么。