Controlling flow with if else
seems like an intuitive default when checking for multiple conditions.
However, I noticed that I’ve been using continue
inside loops more often lately.
Here’s a comparison:
while r < arr.count { if l == r { // ... } else if tempSum >= sum { // ... } else { // ... } }
while r < arr.count { if l == r { // ... continue } if tempSum >= sum { // ... continue } // ... }
I think I prefer continue
over if else
for two reasons:
continue
clearly signals to me that if the condition is satisfied, there’s no need to continue reading the body of the loop. With if else
there’s a chance that the if else
block is followed by more code and it will be executed regardless of the condition.continue
, you clear your mind from the case you just wrote, and proceed to the next case or logic.This is most definitely a personal stylistic preference and I’m not 100% sure if I’m using continue
for the reasons above. Maybe my subconsciousness thinks of arcarde every time it processes the word “continue”, enjoys the memories and asks for more satisfaction — all while I’m struggling to find a sequence within an array that satisfies a certain criteria.
TIL: This pattern is called Return Early and there’re articles out there that cover it in more detail. Here’s the one I particularly enjoyed: