Reuse code for looping through a multidimensional array

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?

+2
java loops command-pattern refactoring
source share
3 answers

What you are looking for is a command template: define an interface with one method and implement it for each use case as an anonymous class. You will pass an instance of this interface to a method that runs the entire template and calls your method only for the interesting part:

 public void forAllMembers(Foo[][] fooArray, Command c) { for (int i = 0; i < fooArray.length; i++) { for (int j = 0; j < fooArray[i].length; j++) { c.execute(fooArray[i][j]); } } } 

Or wait for Java 8 to introduce Lambdas and provide your problem with a first-class solution!

+6
source share

You could do this:

 public void method1(Performer p) { for (int i = 0; i < fooArray.length; i++) { for (int j = 0; j < fooArray[i].length; j++) { p.doIt(fooArray[i][j]); } } } static interface Performer { public void doIt(int ij); } 

then implement different performers and pass them on to this single method.

This approach is called Command Pattern.

+2
source share
 public Baz() { for (int i = 0; i < fooArray.length; i++) { for (int j = 0; j < fooArray[i].length; j++) { fooArray[i][j] = initArray(/* .. */); doSomethingWithFooArray(fooArray[i][j] ); doSomethingElseWithFooArray(fooArray[i][j] ); } } } 

If you want to create something in common, you can use Interface ,

 public interface FooItf{ public void doSomethingWithFooArray(int value ); public void doSomethingElseWithFooArray(int value ); public int initArray(/* .. */); } 

and now you can write something:

  public looping(FooItf foo) { for (int i = 0; i < fooArray.length; i++) { for (int j = 0; j < fooArray[i].length; j++) { fooArray[i][j] = foo.initArray(/* .. */); foo.doSomethingWithFooArray(fooArray[i][j] ); foo.doSomethingElseWithFooArray(fooArray[i][j] ); } } } 

Now you can generate several classes based on FooItf and implement any internal logic.

+2
source share

All Articles