0
The two examples below are equivalent, but what represents the best way to make a if-else
? My goal is to display "num é igual a 0"
if num
is equal to 0, and "num é diferente de 0"
case num
has any other numerical value.
Code 1
if (num == 0)
puts("num eh igual a 0");
else
puts("num eh diferente de 0");
Code 2
if (num != 0)
puts("num eh diferente de 0");
else
puts("num eh igual a 0");
Every time I write one if-else
I brake and I have this doubt, whether I should first treat the specific condition in If
and leave the rest to the Else
as in Code 1, or the other way round, dealing first with most cases in If
and leaving the specific case at Else
as in Code 2.
Another question: suppose I have one if-else
in which the blocks if
and else
have a different amount of lines of code, in which case the order matters? I mean, it makes a difference in the elegance and readability of the code the option that has the most lines of code be written first (within if) or last (within Else)?
Code 1 is generally preferable, but it all depends... the idea is to make the code as quickly understandable as possible and, most of the time, a denial can confuse a little more, but in a data validation section it may make more sense to Code 2. Anyway, it depends on... On the second question, particularly, I have never seen someone with this neura and I think it does not make so much difference, given that if an if/I get too big you can separate it into smaller methods. As a tip, take a look at the book "Clean Code".
– Juciano Victor
Perhaps, depending on the case, there might be some difference in performance because of the branch Prediction, but then you will only know after you test. But at first, "whatever", depends a lot on each case.
– hkotsubo