【发布时间】:2021-12-27 14:07:43
【问题描述】:
我有两个几乎相同的方法来过滤列表并返回过滤后的结果。他们的算法是相同的,不同的是第一个函数返回最频繁的元素,第二个返回最不频繁的元素:
private static List<List<Character>> filter(List<List<Character>> lines, int charIndex) {
List<List<Character>> result = copyList(lines);
List<List<Character>> startWith0 = new ArrayList<>();
List<List<Character>> startWith1 = new ArrayList<>();
for(int i = 0; i < result.size(); i++) {
List<Character> currentLine = result.get(i);
if (currentLine.get(charIndex) == '1') {
startWith1.add(currentLine);
} else if (currentLine.get(charIndex) == '0') {
startWith0.add(currentLine);
}
}
if (startWith1.size() > startWith0.size() ||
startWith1.size() == startWith0.size()) {
return startWith1;
} else {
return startWith0;
}
}
第二个函数的结尾是这样的:
if (startWith1.size() > startWith0.size() ||
startWith1.size() == startWith0.size()) {
return startWith0;
} else {
return startWith1;
}
我认为这种代码重复不是一个好的程序设计,但我没有看到将函数的第一部分和第二部分分成不同方法的好方法。
【问题讨论】:
标签: java refactoring