NOTE: I'm under the impression that you want to avoid logic statements inside loops. This I believe was stated partly because of how the compiler can optimize any loop where iterations behave predictable. While I'm almost certain I've heard this before and for a long time I've thought of this as a convention. Sadly I couldn't find any good references. If this is true however there are some conflicting cases due to the "DRY" principle (Don't repeat yourself).
PRETEXT: Assuming that you have a rather sizable data set, say a multi-dimensional array as I used in this example. Furthermore assume you need to traverse every entry and do some operation on all or some of the elements, and that you need to be able to choose that one or another operation is to be performed. This calls for making two methods where 90%-99% of the code is identical between the two, while only an operator or a method call is different. If this had been C++ I would have wanted to provide a function pointer to a loop function, though I do not know if this too would be preferred avoided.
QUESTION: Would it be preferred to use logic statements and have only one loop or rather two almost identical methods?
EXAMPLE: I've provided some example to show how redundant the "twin" method solution looks:
// This method is provided for completeness of the example
// and to provide some clue as to what boolean parameter and logic statement
// I could alternatively have implemented within the loop method instead of external to it.
public int[][] addOrSubtractArrays(int[][] a, int[][] b, boolean useAdd){
if(a == null || b == null || a.length != b.length || a.length < 1 || a[0].length != b.length)
return null;
return useAdd ? add(a, b) : subtract(a, b);
}
private int[][] add(int[][] a, int[][] b){
int h = a.length;
int w = a[0].length;
int[][] c = new int[h][w];
for(int y = 0; y < h; y++){
for(int x = 0; x < w; x++){
c[y][x] = a[y][x] + b[y][x];
}
}
return c;
}
private int[][] subtract(int[][] a, int[][] b){
int h = a.length;
int w = a[0].length;
int[][] c = new int[h][w];
for(int y = 0; y < h; y++){
for(int x = 0; x < w; x++){
c[y][x] = a[y][x] - b[y][x];
}
}
return c;
}
EXAMPLE 2: The (obvious?) alternative
private int[][] addOrSubtract(int[][] a, int[][] b, boolean useAdd){
if(a == null || b == null || a.length != b.length || a.length < 1 || a[0].length != b.length)
return null;
int h = a.length;
int w = a[0].length;
int[][] c = new int[h][w];
for(int y = 0; y < h; y++){
for(int x = 0; x < w; x++){
if(useAdd)
c[y][x] = a[y][x] + b[y][x];
else
c[y][x] = a[y][x] - b[y][x];
}
}
return c;
}
I am overly tempted to make some common method holding the entire loop structure to avoid (almost) duplicate code. However if "what I've heard" has some reasonable context, this may to my knowledge be best avoided.