Let's say I have a multidimensional array as a member of a class and many methods that go through each element of the array and then work on it. The code might look like this:
public class Baz { private Foo[][] fooArray = new Foo[100][100]; public Baz() { for (int i = 0; i < fooArray.length; i++) { for (int j = 0; j < fooArray[i].length; j++) { // Initialize fooArray } } } public void method1() { for (int i = 0; i < fooArray.length; i++) { for (int j = 0; j < fooArray[i].length; j++) { // Do something with fooArray[i][j] } } } public void method2() { for (int i = 0; i < fooArray.length; i++) { for (int j = 0; j < fooArray[i].length; j++) { // Do something else with fooArray[i][j] } } } // and so on }
Now, since the loop code is always the same, only the operation in the loop changes, is there a way that the loop code can be somehow reorganized into a separate method? It would be so nice to be able to do
doInLoop(functionToExecute());
What will be the closest replacement to do something like this, if possible?
java loops command-pattern refactoring
subarachnid
source share