首页 > 解决方案 > 如何重构输入参数的嵌套修改?

问题描述

TestClass的func1方法调用了fillIdsAndNames,不同的fillIdsAndNames函数内部修改了Ids和names,很臭。是否可以通过重构和设计模式消除不良气味,而不会导致其他不良气味。

interface Computable {
    void fillIdsAndNames(Integer num, Set<String> ids, Set<String> names);
}

@Component
class Class1 implements Computable {
    @Override
    public void fillIdsAndNames(Integer num, Set<String> ids, Set<String> names) {
        Set<String> candidateIds = computeFunc1(num);
        candidateIds.stream().filter(id -> !ids.contains(id)).forEach(id -> {
            ids.add(id);
            names.addAll(someFunc1(id));
        });
    }
}

@Component
class Class2 implements Computable {
    @Override
    public void fillIdsAndNames(Integer num, Set<String> ids, Set<String> names) {
        if (ids.contains(num)) {
            return;
        }
        Set<String> candidateIds = computeFunc2(num);
        for (String id : candidateIds) {
            if (judgeFunc(id)) {
                ids.add(id);
            } else {
                names.add(someFunc2(id));
            }
        }
    }
}

@Component
public class TestClass {
    @Autowired
    private Map<Integer, Computable> map;
    
    void func1(List<Integer> nums) {
        Set<String> ids = new HashSet<>();
        Set<String> names = new HashSet<>();
        for (Integer num : nums) {
            Computable computer = map.get(num);
            computer.fillIdsAndNames(num, ids, names);
        }
        .....
    }
}

标签: javadesign-patternsrefactoring

解决方案


推荐阅读