我试图弄清楚使用 VAVR 的 Try 的惯用方式是什么。我正在查看的用例必须执行以下步骤:
- 获取鞋子列表(调用可以抛出检查异常)
- 清理每只鞋子(调用可以抛出检查异常)
- 恢复每只鞋子(调用可以抛出已检查的异常)
- 返回清洁/修复鞋子的列表
这是我的示例玩具代码,其中 processRequest 方法购买了 n 双鞋,清洁并修复它们;打印错误(如果有):
// definitions
ShoeStore java.util.List<Shoe> buy(int numberOfPairs) throws OutOfStockException;
ShoeCleaningService Shoe clean(Shoe dirtyShoe) throws OutOfShoePolishException;
ShoeRestoreService Shoe restore(Shoe oldShoe) throws OutOfSparePartsException;
class EnterpriseShoeService {
// constructor
...
public List<Shoe> processRequest(int numberOfPairs) {
Try<List<Shoe>> shoes = Try.of(() -> shoeStore.buy(numberOfPairs));
Try<List<Try<Shoe>>> cleanedAndRestoredShoes = shoes.map(xs -> xs.stream().map(shoe ->
Try.success(shoe)
.andThenTry(shoeCleaningService::clean)
.andThenTry(shoeRestoreService::restore))
.collect(Collectors.toList()));
List<Shoe> result = cleanedAndRestoredShoes
.getOrElseGet(err -> {
System.out.println(err.getMessage());
return Collections.emptyList();
})
.stream()
.map(shoeTry -> shoeTry.onFailure(err -> System.out.println(err.getMessage())))
.filter(Try::isSuccess)
.map(Try::get)
.collect(Collectors.toList());
return result;
}
}
我的问题是:如何简化这个逻辑?有没有可以消除的方法调用?可读性可以提高吗?