As I couldn't find a question similar to my construct, I am going to ask it.
I have following code:
for (Object o : array1) {
for (Object o2 : array2) {
if (condition1) {
//get a variable for condition2 (depends on iteration elements)
if (condition2) {
if (condition3) {
//do something
} else if (condition4) {
//do something
}
}
}
}
}
I could also write it as
for (Object o : array1) {
for (Object o2 : array2) {
if (condition1 && condition3) {
// get a variable for condition2 (depends on iteration elements)
if (condition2) {
// do something
}
} else if (condition1 && condition4) {
// get a variable for condition2
if (condition2) {
// do something
}
}
}
}
which would work the same way. In the first example, I tried to use code multiple times as much as possible, where as in the second example I had to use the same code multiple times.
Now I read on this question, that one should avoid nesting if possible. Yet in my understanding it is also cleaner not to have the same code multiple times which I would have in the first example.
My question is, should one avoid nesting on the cost of having the same code multiple times? I am asking about best practices/standards here and not opinions.
I know that I could move it into a separate method, but in the end I would probably have about the same amount of code.
EDIT:
With the help of Lino's answer and comments I came up with following construct:
for (Object o : array1) {
// get a variable for condition2 (depends on iteration elements)
if (condition2) {
for (Object o2 : array2) {
if (condition1) {
if (condition3) {
// do something
} else if (condition4) {
// do something
}
}
}
}
}