News for hackers. Stuff that matters.
Re:Push ifs up and fors down by quickthrower2 on Wednesday November 15, 2023 @09:57PM (#38285410)
In short: avoid `else`.

Both what you mention, and also the case with :

   if (...) {
     ...
   } else { 
     return 0; 
   }
Which can become

   if (...) {
     ...
   }

   return 0;
Re:Push ifs up and fors down by hedora on Wednesday November 15, 2023 @10:06PM (#38285452)
Even better, if you're using a language with pattern matching (rust, any ML, haskell), just put it in a single match with the happy case on top, and the error cases below.

To do this, you need to encode the distinction between happy and sad path in your types. That's good for all sorts of other reasons, so it's not really a drawback.

Re:Push ifs up and fors down by KineticLensman on Thursday November 16, 2023 @05:19AM (#38287771)
Yes, pattern matching really helps with clarity, especially when there are multiple happy paths, like in a parser
Re:Push ifs up and fors down by theteapot on Thursday November 16, 2023 @12:18AM (#38286021)
What about `else if`? Not a fan?
Re:Push ifs up and fors down by quickthrower2 on Thursday November 16, 2023 @12:38AM (#38286127)
Occasional vice for me.
Re:Push ifs up and fors down by stouset on Thursday November 16, 2023 @01:25AM (#38286333)
Personally I only either use if statements that wrap a single line of logic, or a switch/case statement where each branch is a single line of logic.

Most situations are handled by guard clauses, exhaustive type switching, or switching on logical cases. Very occasionally do I have to break this practice for a legitimate reason, but this keeps functions simple to read and to reason about.

I occasionally am unable to avoid an else, but I will always avoid else if. It puts too much reliance on remembering how this condition interacts with the one on the if statement above it, which can often be many lines away. I’d infinitely rather use a case statement where all the alternatives are in an easily-understood table with every condition aligned on successive lines.

Re:Push ifs up and fors down by Xeamek on Thursday November 16, 2023 @01:30AM (#38286349)
In functional languages like elixir there is no return though, and you are forced to use if-else structure
Re:Push ifs up and fors down by jstanley on Thursday November 16, 2023 @06:37AM (#38288328)
I tend to prefer a style more like:

    if (!...) return 0;

    ...
Because otherwise you can end up with lots of nested conditions which are very confusing to follow, even though they boil down to "do the thing if these are true, otherwise don't do the thing".