Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditions in loops, best practices?

Say I have a loop like this:

for (int i = 0; i < someint; i++)
{
    if (i == somecondition)
    {
        DoSomething();
        continue;
    }
    doSomeOtherStuff();
}

Versus...

for (int i = 0; i < someint; i++)
{
    if (i == somecondition)
    {
        DoSomething();
    }
    else
    {
        doSomeOtherStuff();
    }
}

Is there any reason to use one over the other? Or is it just personal preference?
The main language I'm asking this for is Java, but I guess it also applies to most others.

like image 480
Josh Avatar asked Jan 17 '12 15:01

Josh


2 Answers

Technically, no, but I find the second one prettier for this particular case.

like image 170
Michael Krelin - hacker Avatar answered Oct 01 '22 20:10

Michael Krelin - hacker


I prefer the second construct...

for (int i = 0; i < someint; i++)
{
    if (i == somecondition)
    {
        DoSomething();
        //lets say lot of code
        //..
        //...
        //...
        //...
        continue;
    }
    else
    {
        doSomeOtherStuff();
    }
}

Lets say you had lot of code before the continue. It is immediately apparent just by looking

   else
    {
        doSomeOtherStuff();
    }

the it is not executed unconditionally.

like image 35
parapura rajkumar Avatar answered Oct 01 '22 21:10

parapura rajkumar