This may be a little subjective, but I have often found that it can be very interesting to see how other developers approach certain daily details.
I have code which works like this:
class A {
public List<SomeType> getOneSet() { ... }
public List<SomeType> getAnotherSet() { ... }
}
class B {
public static OtherType convert(SomeType input) { ... }
}
// ...
A a = new A();
List<OtherType> rgResults = new ArrayList<OtherType>();
And now would follow the equivalent of two identical for
loops, like so:
for (SomeType input : a.getOneSet()) {
rgResults.add(B.convert(input);
}
for (SomeType input : a.getAnotherSet()) {
rgResults.add(B.convert(input);
}
This works, but it's of course code duplication. If the code inside the loop gets a little more complicated or there's more than two sets it's not acceptable.
I therefore put the loop in a function that takes source and destination list as a parameter, but was curious to see if there are other ways. Especially ones that might be more appropriate when you're never calling the function from more than one place.
For example I would have liked the following, which didn't work because I can't have arrays of generics:
for (List<SomeType> rgSrc : new List<SomeType>[] { a.getOneSet(), a.getAnotherSet() } ) {
for (SomeType src : rgSrc) {
rgResults.add(B.convert(src));
}
}