Dup Ver Goto 📝

WhyElseIsntThatBad

PT2/lang/style does not exist
To
45 lines, 411 words, 2224 chars Page 'WhyElseIsntThatBad' does not exist.

Often I see channels on youtube where they are religious about avoiding else clauses and nesting. Their solution is to split things up into lots of separate functions, oblivious to both the lack of locality in the source code, so that control flow jumps up and down may lines, essentially at random.

The problem with the 'move it into its own function' thing is that you lose locality: you have to jump between two or more parts of your code to see what a function is doing, rather than having it all in front of your eyes in a single screen. Sure in vim it's not too bad as you can easily open splits to view multiple parts of your source code at the same time. All you're really doing is using return as a de facto goto, and functions as a syntactic means of creating gotos to jump around in code so as to avoid using else.

I get the guard clauses thing. I use them whenever it is convenient to do so. But I prefer if things are in a single screenful rather than having to jump between different function definitions and then having to remember what was in function foo()'s definition while reading function bar(). With everything on the screen at once, I only have to move my eyes, not move the cursor around the code.

Consider this in C:

int main(int argc) {
  if( argc < 1 ) {
    printf("no args\n");
    goto next1;
  }
  printf("args\n");
next1:
  printf("now we are here\n");
}

by using goto, you've avoid using else. Yay! no else!. Or you could do

int main(int argc) {
  foo(argc) // basically this is a goto to X1 below
  // X2
  printf("now we are here\n");
}

// now imagine you have 100 lines of code here so that if foo() is on your screen, then main() isn't and vice versa.

void foo(int argc) {
// X1
  if( argc < 1 ) {
    printf("no args\n");
    return; // and this is basically a goto back up to X2 above
  }
  printf("args\n");
}

Having control flow needlessly jump around the source code, so as to avoid writing else, doesn't improve readability. Rather it turns your code into one of those Choose Your Own Adventure books where you read a page of the story, then jump forward 50 pages to see what's next, and then jump back 20 pages, and then perhaps back to where you started.