mardi 25 juillet 2017

Is it a bad practice to place conditional statements inside iterations?

So let's consider the case where there is the below snippet:

if(x = 0)
{
     for(var i = 0; i < 5; ++ i)
     {
         //do something  
     }
}
else
{
   for(var i = 0; i < 5; ++ i)
     {
         //do something different
     }
}

As you can see, both of the conditions iterate through the same for loop but perform different actions based on the condition. My question is, is it a bad practice to have something like this:

for(var i =0; i < 5; ++ i)
{
     if(x = 0){
       // do something
     }else{
        // do something else
     }
}

The reason being that I think that this may be a bad practice is due to the fact that for every instance of the loop, a conditional check is being executed on it against the first snippet where he condition is checked first and then the loop is executed. Am I mistaken?

Aucun commentaire:

Enregistrer un commentaire