I'm too often facing situations where I need to get several types of information from a method. I usually think long and hard to circumvent these situations but I'm thinking it's pointless work that I'm doing. My question: should I prefer to take a slight performance hit in these situations, like iterating over an array twice for example (resulting in slower but cleaner code) or try to return everything at once with an instance of a custom helper class?
Here's a case example for the sake of it
char[] arr = {'a', 'b', 'a', 'c', 'a'};
int count = 0; // 'a' and 'b' count
String word= ""; // 'a's and 'b's glued together in their occurring order
for (int i = 0; i < arr.length; ++i) {
for (int j = 0; j <= arr[0].length; ++j) {
if (arr[i][j] == 'a' || arr[i][j] == 'b') {
++count;
word += Character.toString(arr[i][j]);
}
}
}
// return both 'count' and 'word' inside a new object or iterate twice?
someString += moreStuff;in Java. I've got a blog post on that - What goes on behind the scenes of += with String in Javacountis simplyword.length().(for j...)loop? And you could just writereturn new String(arr).replaceAll("[^ab]", "")?