Hey,
I have two methods, one which counts the number of objects which are considered to have a lower value than a given object, and another which counts the number of objects which have a higher value than a given object. As you can probably tell, the two methods are practically identical:
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;
}
I've refactored the methods to call a private method:
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;
}
But I do not find this solution satisfying. It would be possible to call the private method with an invalid integer (i.e. 10), and the additional error checking for this case is fairly ugly:
if (comparison < -1 || comparison > 1)
{
throw blah
}
Using a boolean is also unsatisfactory, since in the future it is reasonably possible that I may want to count the number of objects of equal value.
Do you have an alternative refactoring solution?
Cheers,
Pete