At the beginning of a function that requires a lot of condition checks, sometimes I prefer to do the first option to reduce nested if-statements. Is this a good or bad programming practice?
2 Likes
This is called a “guard” Guard (computer science) - Wikipedia
Inverting if statements to reduce nesting is a good idea, it makes code much easier to follow.
10 Likes
Just remember that, due to precendence:
if not 3 == 2 then
-- stuff
end
is not the same as
if 3 ~= 2 then
-- stuff
end
The first one negates a, then does the equality comparison. The second does an inequality comparison. The first one won’t execute its body (not 3
== false
, which is not equal to 2
) while the second one will!
15 Likes
I really ought to read through Lua manuals again. I feel stupid for not realising that “if not condition then” negates the condition then checks. I’ve had so many problems with my if statements in the past and this misconception or lack of knowledge was the sole perpetrator.
That post will save me years.
3 Likes