函数式编程将代码转换为声明式

时间:2019-05-20 05:55:35

标签: java functional-programming

我有一个这样的for循环。

for (int i = 0; i < filePaths.size(); i++) {
  String filePath = filePaths.get(i);
  Mat mat = Imgcodecs.imread(filePath);
  Mat gray = new Mat();
  cvtColor(mat, gray, 6);

  if (i != filePaths.size()-1) {
       threshold(gray, gray, 150, 255, THRESH_TRUNC);

   }
  Imgcodecs.imwrite(filePath, gray);
}

是否可以将其转换为声明性代码。

谢谢。

1 个答案:

答案 0 :(得分:0)

我想您想在应用程序中使用某种功能样式,并将此命令式代码样式删除为功能代码样式?

因此,如果我理解正确,则应该采取一些其他措施。首先,您必须创建DTO(数据传输对象)以通过逻辑的这一部分。

String filePath = filePaths.get(i);
Mat mat = Imgcodecs.imread(filePath);

您创建此DTO:

class FilePathDTO {
        private final String filepath;
        private final Mat mat;
        private final Mat grey = new Mat();
        private final boolean isNotLastFilepath;

        public FilePathDTO(String filepath, Mat mat, boolean isLast) {
            this.filepath = filepath;
            this.mat = mat;
            this.isNotLastFilepath = isLast;
        }

        public String getFilepath() {
            return filepath;
        }

        public Mat getMat() {
            return mat;
        }

        public Mat getGrey() {
            return grey;
        }

        public boolean isNotLastFilepath() {
            return isNotLastFilepath;
        }
    }

然后,代码将如下所示:

filePaths.stream()
                .map(filePath -> new FilePathDTO(filePath, Imgcodecs.imread(filePath), filePaths.indexOf(filePath) != filePaths.size() - 1))
                .forEach(dto -> {
                    cvtColor(dto.getMat(), dto.getGrey(), 6);

                    if(dto.isNotLastFilepath) {
                        threshold(dto.getGrey(), dto.getGrey(), 150, 255, THRESH_TRUNC);
                    }

                    Imgcodecs.imwrite(dto.getFilepath(), dto.getGrey());
                });

但是,您有一些副作用,例如

if(dto.isNotLastFilepath) {
    threshold(dto.getGrey(), dto.getGrey(), 150, 255, THRESH_TRUNC);
}

并且您根本不会摆脱命令式代码样式。您可以使代码更接近功能。

相关问题