我有两个方法,一个计算被认为具有比给定对象更低值的对象的数量,另一个计算具有比给定对象更高值的对象的数量.你可以说,这两种方法实际上是相同的:
public int countHigher(SomeObject a){
if (a == null){
throw etc...
}
int numberHigher = 0;
for (SomeObeject b : this.listOfSomeObjects) {
if (b.compareTo(a) == 1) {
numberHigher++;
}
}
return numberHigher;
}
public int countLower(SomeObject a){
if (a == null){
throw etc...
}
int numberLower = 0;
for (SomeObeject b : this.listOfSomeObjects){
if (b.compareTo(a) == -1){
numberLower++;
}
}
return numberLower;
}
Run Code Online (Sandbox Code Playgroud)
我重构了调用私有方法的方法:
private int coun(SomeObject a, int comparison){
if (a == null){
throw etc...
}
int number = 0;
for (SomeObeject b : this.listOfSomeObjects){
if (b.compareTo(a) == comparison){
number++;
}
}
return number;
}
Run Code Online (Sandbox Code Playgroud)
但我觉得这个解决方案并不令人满意.可以使用无效的整数(即10)调用private方法,并且对这种情况进行额外的错误检查是相当丑陋的:
if (comparison < -1 || comparison > 1)
{
throw blah
}
Run Code Online (Sandbox Code Playgroud)
使用布尔值也不能令人满意,因为将来我可能想要计算相等值的对象数.
您是否有其他重构解决方案?
干杯,
皮特
我会怎么做:
int comparison参数.这将给你正确分开的关注点.