Sometimes from a collection, several information needed to be extracted.
But what is the best practice to do that?
Should the collection have to be iterated for any information separately? Then we would have n-time loops which goes on the performance.
On other hand, the approaches are easy to understand since it is easy to read which information is extracted from the collection.
Simple Example:
int max = determineMax(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7)));
int sum = calculateSum(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7)));
...
private int determineMax(ArrayList<Integer> integers) {
int max = 0;
for (Integer oneInteger : integers) {
max = Math.max(max, oneInteger);
}
return max;
}
private int calculateSum(ArrayList<Integer> integers) {
int sum = 0;
for (Integer oneInteger : integers) {
sum += oneInteger;
}
return sum;
}
Another solution is to loop once, but then many variables need to be returned. For this approach, we need to use an array or create an artificial class for the return values.
Simple Example:
int[] extractedInformation = extractInformation(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7)));
...
private int[] extractInformation(ArrayList<Integer> integers) {
int sum = 0;
int max = 0;
for (Integer oneInteger : integers) {
sum += oneInteger;
max = Math.max(max, oneInteger);
}
return new int[]{sum, max};
}
You may crave for performance, but in the real world where projects are so big and you're not the only person working on it.
I would say readability and maintainability should get preference more than performance. The example you've provided does not follow encapsulation.
It is recommended that one method should do only one thing and the method name should reflect that one thing.
You can sometimes don't follow it and go for performance, but only in cases the performance degradation is noticeable.
And you generally only get a noticeable difference when the time complexity is differed by some power, like O(n), O(n2).
Although the second one seems to works faster indeed, it is. But both of them are still be called linear because O(n) + O(n) does not make 2*O(n).
In short, computers are too fast nowadays. You should not give up readability and maintainability for minor performance gain.
And your example is an extreme case. Most of the time you will not encounter this kind of thing. Think about if you need sum only or may max only. You will be defining two more methods, and otherwise you will get two things when you ask for one and that is not good for performance either.
It also depends on what you're going to do most of the times.