marc1886
marc1886

Reputation: 158

For loop based on condition check

I am looking for the best approach to write the following code.

if (condition == true)
for (i = 0; i < 200; i++)
{
/// 600 lines of code
}

else
for (i = 200; i > 0; i--)
{
/// same 600 lines of code as in above condition check
}

As of now, I have the same code copied inside both loops. However is there a way to do a check and then have the code appear only once? The only thing that depends upon the condition check is the way the loop will work. I have to go forward or backward in the loop as per the condition check and don't want to have the same 600 lines of code pasted twice. I am writing this in C.

Upvotes: 4

Views: 852

Answers (1)

tobias_k
tobias_k

Reputation: 82929

Instead of having two loops with slightly different loop variables, you could just alter the loop variable depending on the condition so it effectively either counts from 0 up to 200 or from 200 down to 0.

for (iteration = 0; iteration < max; iteration++)
{
    index = (condition == true)  ?  iteration  :  max-iteration;
    //  600 lines of code, using index
}

You might want to add a comment to that, so others (and you, later) know what this is supposed to do.

However, even then you should probably try to refactor those 600 lines of code to a separate method -- or rather several separate methods, each handling one aspect of those 600 lines. As a rule of thumb: i) Whenever you have repeated code, no matter whether its 600 lines or just 10 lines, try to make it a method, and ii) whenever you have a really long block of code, even if it's not repeated many times, try to split it up into several methods. This will make the code more self-descriptive and much easier to maintain.

This might not always be easy, e.g. if those 600 lines access and modify many variables declared outside of the loop, but then again, this in itself might be another flaw in design...

Upvotes: 1

Related Questions