繁体   English   中英

如何减少 Java 8 中的重复代码?

[英]How can i reduce this repeat code in Java 8?

我有以下代码不断重复。 也许有办法减少它,但我不太了解 java。 它看起来像这样:

public Optional<byte[]> generateReportA(List<ClassThatChange> request){
        if(CollectionUtils.isEmpty(request)) {
           return Optional.empty();
        }
        
        List<ClassThatNOChange> list = new ArrayList<>();

        
        for(ClassThatChange item : request){
            ClassThatNOChange c = new ClassThatNOChange()
            
            //here is the line of code that changes from report to report
            c.setResult(callMethodA(item.getVariable1(), item.getVariable2()));

            list.add(c);
        }
        
        return Optional.of(callSameMethod(list));
}

public Optional<byte[]> generateReportB(List<ClassThatChange> request){
        if(CollectionUtils.isEmpty(request)) {
           return Optional.empty();
        }
        
        List<ClassThatNOChange> list = new ArrayList<>();

        
        for(ClassThatChange item : request){
            ClassThatNOChange c = new ClassThatNOChange()
            
            //here is the line of code that changes from report to report
            c.setResult(callMethodB(item.getVariable2()));

            list.add(c);
        }
        
        return Optional.of(callSameMethod(list));
}

唯一改变的是 callMethodA 或 B 或 C ......但它们都返回相同类型的答案。

ClassThatChange 是这样的:

public class Father{
      private Date date;
      // then the getters and setters
}

public class Son extends Father{
      private String description;
      // then the getters and setters
}

所有可以改变的类都继承自父类。

有没有办法减少这个重复代码? 对不起,我的英语不好。

我认为您正在寻找的是一种插入从在每种情况下更改的类型到始终相同的类型的转换的方法。 这可以通过Function或您定义的自定义功能接口来完成。 在这里,我展示的是Function

private <T> Optional<byte[]> convert(
    List<? extends T> request, 
    Function<? super T, ? extends SomeTypeYouDidNotShow> conversion) {

    if (request.isEmpty()) return Optional.empty();
    List<ClassThatNOChange> list = request.stream()
        .map(item -> {
                ClassThatNOChange c = new ClassThatNOChange();
                c.setResult(conversion.apply(item));
                return c;
            })
        .collect(Collectors.toList());
    return Optional.of(callSameMethod(list));
}

然后你所有的重复方法看起来像这样:

public Optional<byte[]> generateReportA(List<Father> request) {
    return convert(request, 
        item -> callMethodA(item.getVariable1(), item.getVariable2()));
}

public Optional<byte[]> generateReportB(List<Son> request) {
    return convert(request, 
        item -> callMethodB(item.getVariable2()));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM