java - 如何重构输入参数的嵌套修改?
问题描述
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);
}
.....
}
}
解决方案
推荐阅读
- java - 如何删除部分数组中的所有 char 重复项(未排序且不应该排序)
- reactjs - 有没有办法在 Component Mount 上调度一个动作?
- nginx - 同时使用 Varnish 和 Nginx 缓存
- python - 如何在 Python 中使用户输入不区分大小写?
- c - 如何启动我的 malloc 和 free 程序的前 2 个功能?
- python - 如何在 python 中的烧瓶应用程序中调用 asyncio 函数
- python - 如何修复 ValueError:检查目标 Keras 时出错
- c# - 文件已被无限循环中的另一个进程使用
- c# - 如何在 C# 中删除 Yaml 文件末尾的 3 个点?
- browser - HREF target='_blank' 在 Chrome 79 中不起作用