I try to make some code more readable (and thus maintainable). Let's start with the current iteration of the code:
int[] outerIterations = getDataToIterateOver();
for (int i : outerIterations) {
for (int j : outerIterations) {
if (i == j) continue;
for (int a : getDataByIndex(i)) {
for (int b : getDataByIndex(j)) {
function1();
function2();
}
}
}
}
It had some further nesting which I could already reduce, but I am still looking for how to write the code to have less nesting.
I am not a Java developer but doing C# and Golang, so I think I'm missing on some language feature that might help me here.
Used Java version: 17
CodePudding user response:
so I think I'm missing on some language feature
I guess it's not related to specific features of Java.
When you have a lot of actions creamed into a method, most likely you are dialing with a violation of the Single-responsibility principle.
I understand that you've proved a simplified code-sample. Have a closer look at what your method is doing and which of these actions can be extracted out from it.
That's a dummy example on how to reduce the level of nesting.
public void doSomething() {
int[] outerIterations = getDataToIterateOver();
for (int i : outerIterations) {
for (int j : outerIterations) {
if (i == j) continue;
doSomethingWithIJ(i, j);
}
}
}
public void doSomethingWithIJ(int i, int j) {
for (int a : getDataByIndex(i)) {
for (int b : getDataByIndex(j)) {
function1();
function2();
}
}
}
In case, if you assumed that this code could be made to be functional in style, i.e. to utilize Stream API instead, then you need to provide something close to the actual code. For now, it doesn't seems like you can apply functional programming here.