java - VAVR 撰写尝试和列表

标签 java functional-programming vavr

我正在尝试找出使用 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;

    }
}

我的问题是:如何简化这个逻辑?有没有可以消除的方法调用?能否提高可读性?

最佳答案

我不知道是否一切都按预期工作,因为没有提到要求,但这应该让您了解分解的能力。

import io.vavr.collection.List;
import io.vavr.control.Try;


public class TryListComposition {

   ShoeStore store;

   ShoeCleaningService cleaningService;

   ShoeRestoreService restoreService;

   public java.util.List<Shoe> processRequest(int numberOfPairs) {
    return processShoesRequest(numberOfPairs).getOrElse(List.empty()).toJavaList();
   }

   public Try<List<Shoe>> processShoesRequest(int numberOfPairs) {
      return this.buy(numberOfPairs)
            .map(shoes -> shoes
                    .map(this::cleanAndRestore)
                    .flatMap(x -> x)
            );
   }

   public Try<Shoe> cleanAndRestore(Shoe shoe) {
      return clean(shoe).flatMap(this::restore);
   }


   Try<List<Shoe>> buy(int numberOfPairs) {
      return Try.of(() -> 
        List.ofAll(store.buy(numberOfPairs).stream());
   }

   Try<Shoe> clean(Shoe dirtyShoe) {
      return Try.of(() -> cleaningService.clean(dirtyShoe));
   }

   Try<Shoe> restore(Shoe oldShoe) {
      return Try.of(() -> restoreService.restore(oldShoe));
   }

}

class Shoe {

}

interface ShoeStore {
   java.util.List<Shoe> buy(int numberOfPairs) throws 
   OutOfStockException;
}

interface ShoeCleaningService {
   Shoe clean(Shoe dirtyShoe) throws OutOfShoePolishException;
}

interface ShoeRestoreService {
   Shoe restore(Shoe oldShoe) throws OutOfSparePartsException;
}

class OutOfStockException extends Exception {

}

class OutOfShoePolishException extends Exception {

}

class OutOfSparePartsException extends Exception {

}

关于java - VAVR 撰写尝试和列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56068599/

相关文章:

java - 为什么不能所有 Functor 都是 Monad?

java - Vavr 对象的序列化器/反序列化器

java - Hibernate 6 Left Join 集合的最新成员

haskell - 为什么会出现 "Last generator in do {...} must be an expression"错误?

java - 将数组中的数字转换为另一个数组

list - 仅使用 `!!` 和 `length` 实现矩阵的转置

oop - 在 Haskell 中编程时如何纠正我的 OOP 倾向

java - 将一系列 void 函数应用于单个值的函数式编程习惯

java - 使用 setDisplayHomeAsUpEnabled 返回 list 中的 PARENT_ACTIVITY 时出现问题

java - 如何使 Mapper 从具有公共(public)列的两个不同文件中获取输入?