Reputation: 1581
If you want to get at some point both negative or positive numbers from an array, which option would be 'better':
getAllNumbers(initialArray, boolean positive)
....
or
getAllPositiveNumbers(initialArray){
....
}
getAllNegativeNumbers(initialArray){
...
}
Upvotes: 0
Views: 110
Reputation: 51393
I would like to use getAllPositiveNumbers
and getAllNegativeNumbers
since the code is more clear to read, but it might be reasonable to provide a convenience method for clients.
If the client code must select one of the methods at runtime (because of user input). Then every client must do something like this:
boolean selectPositiveNumber = .....; // obtained somehow through user input
int[] numbers = null;
if(positiveNumbers){
numbers = getAllPositiveNumbers(allNumbers);
} else {
numbers = getAllNegativeNumbers(allNumbers);
}
In this case the convenience method getAllNumbers(initialArray, boolean positive)
makes the client code easier.
boolean selectPositiveNumber = .....; // obtained somehow through user input
int[] numbers = getAllNumbers(allNumbers, selectPositiveNumber);
If the client code selects one of the methods at 'compile time'. Then the client doesn't need a convenience method, e.g. a client code might do something like this:
public int positiveSum(int[] values){
int[] positiveNumbers = getPositiveNumbers(values);
int sum = 0;
// loop to calc the sum
return sum;
}
Fortunately you can combine both:
public int[] getAllNumbers(int[] nums, boolean onlyPositiveNums){
if(onlyPositiveNums){
return getAllPositiveNumbers(nums);
} else {
return getAllNegativeNumbers(nums);
}
}
So if you expect a lot of client code which does an if/else
than provide a convenience method.
Upvotes: 1
Reputation: 551
If this is for a library or something, I'd recommend to use both. The getAllPositiveNumbers and getAllNegativeNumbers methods could call the getAllNumbers method, like so:
public int[] getAllNumbers(int[] array, boolean positive) {
//...
}
public int[] getAllPositiveNumbers(int[] array) {
return getAllNumbers(array, true);
}
Otherwise use whichever you prefer.
Upvotes: 0
Reputation: 27356
Personally, I'd go for getAllPositiveNumbers
. Otherwise, you'll need to write a fair few comments in getAllNumbers
to make it as instantly obvious the former.
Example
/**
* Returns numbers from an array.
* @positive boolean value indicating to get just positive values or not.
*
*/
public List<Integer> getAllNumbers(initialArray, boolean positive)
{
// Some code.
}
Or
public List<Integer> getAllPositiveNumbers(int[] numbers)
{
// Some code.
}
As you can see, the last one is pretty obvious what it does.
Upvotes: 0