我已经阅读过类似的帖子,但这是使用 computeIfAbsent 函数的正确方法吗?cookieMap 是一个 HashMap,响应是一个对象,其中包含所有标题、cookie、响应、状态代码等...cookieMap.computeIfAbsent("Varlink", varLink -> { if (responses.getCookie("VARLINK").length() < 1) { throw new ProviderException("Varlink not present in response, check response status!!!"); } return responses.getCookie("VARLINK");});我需要向 cookieMap 添加多个这样的键。我最初的想法是将所有内容都放在 If 条件中,但由于某些限制,我们不应该嵌套 if-else 条件(我猜 Code Reviewer 对 Clean Code 这本书太认真了)
1 回答
蝴蝶刀刀
TA贡献1801条经验 获得超8个赞
如果responses和cookieMap是两个不同的数据源,那么您的代码段是正确的。唯一的问题是调用cookieMap::getCookie两次,这可能会使用有人在评论中建议的变量来解决。
我会使用以下方法缩短整个表达式Optional:
cookieMap.computeIfAbsent("Varlink", v -> {
Optional.of(respones.getCookie("VARLINK")) // Gets a cookie
.filter(c -> c.length() >= 1) // Filters the length
.orElseThrow(() -> new ProviderException("...")); // Returns only if present
});
添加回答
举报
0/150
提交
取消