0

Quite often I have an if statement where I have two cases, one of which requires a one-liner and one of which needs lots of code to be dealt with. From a readability point of view, which should I put first, given that I don't know how likely each one is? So:

if(flag) {
    // lots and lots and lots of code
    // blah
    // blah
    // blah
    // blah
    // blah
    // blah
    // etc
} else {
    // easy one liner
}

compared to

if(!flag) {
    // easy one liner
} else {
    // lots and lots and lots of code
    // blah
    // blah
    // blah
    // blah
    // blah
    // blah
    // etc
}

Note: This is not a performance question, but a readability/ease of maintenance one.

Bluefire
  • 13,519
  • 24
  • 74
  • 118

2 Answers2

1

I find having the else as close as possible to the original "if" so I can see that it's there. Your examples are short, so it doesn't really matter, but it seems to when the strophes get long.

What I actually prefer is to lose the else and write:

If (flag){
...
}

if (!flag){
...
}
Robert Moskal
  • 21,737
  • 8
  • 62
  • 86
1

Also for a better readability, if you have lots and lots of code in the first brackets, why not extract this code into a separate function?

(if flag){
  foo(parameters);
}
else
{
//one liner
}
Antoine Lefebvre
  • 346
  • 3
  • 10