I have a general design question. Suppose I have a List
:
List<String> list = new ArrayList<>();
list.add("Str 1");
list.add("Str 2");
list.add("Str 3");
I need to process the elements of that list in a loop. There are at least 3 options that I can think of.
Passing only the list the perform the operations:
public List<String> processListInLoop(List<String> list) {
for (int i = 0; i < list.size(); i++) {
// do something with the element
// list.get(index).
}
return list;
}
Passing the list with the index of an element:
public List<String> processListWithIndex(List<String> list, int index) {
// do something with the element
// list.get(index).
return list;
}
Passing the element directly:
public String processElement(String str) {
// do something with the element
// str.
return str;
}
The methods would be called like this:
// option 1
processListInLoop(list);
// option 2
for (int i = 0; i < list.size(); i++) {
processListWithIndex(list, i);
}
// option 3
for (int i = 0; i < list.size(); i++) {
list.add(processElement(list.get(i)));
}
Is there a rule about the granularity of a method? My guess would be to use option 1, as that method encapsulates most of the logic.