I'm currently implementing an algorithm that constructs a matrix-pattern based on mathematical formulas. To achieve this I use deeply nested for-loops and alot of if-conditions in it. The problem is, that I cannot split the loop into multiple method without providing a lot of parameters. And for now the code looks like an undesired spaghetti-code.
Here is a small pseudo-example:
int steps = 10;
void evaluate( int numOuterArea , int numInnerArea , int[] solution , int[] factor , int[] indices )
{
int counterA = 0;
int counterB = 0;
for( int outerAreaIter = 0 ; outerAreaIter < numOuterArea ; outerAreaIter++ )
{
for( int curOuterAreaIter = 0 ; curOuterAreaIter < steps ; curOuterAreaIter++ )
{
for( int innerAreaIter = 0 ; innerAreaIter < numInnerArea ; innerAreaIter++ )
{
for( int curInnerAreaIter = 0 ; curInnerAreaIter < curOuterAreaIter ; curInnerAreaIter++ )
{
if( curInnerAreaIter == curOuterAreaIter )
{
// do something with solution, factor or indices
}
else if( /* some other fancy condition */)
{
}
...
}
}
}
}
// similar nested loops follow here
}
If I would write classes/methods for each loop or part of a loop, I have to provide all parameters from evaluate() (which can be even more as shown in the example) and also all previous iterators and possible variables.
Is there a way/common practice/any hints or advice to rewrite such code in a better way?
evaluate()functions and also inside the functions there are several different implementations. Also the conditions, variables and so on change every time.