Nested IF statements or extra conditionals?

For the challenge of only moving the character if the mouse mode was captured I just added the conditional to the original IF statement:

	if event is InputEventMouseMotion && Input.mouse_mode == Input.MOUSE_MODE_CAPTURED:
		mouse_motion = -event.relative * 0.001

Is there a particular reason to used nested IF statements over extending conditionals?

Yup - that scrollbar that appeared under your code block in this post =)

Joking aside, both approaches are fine, and this is more about refactoring after you’ve already built a working solution. Nested if-statements are arguably more human-readable because they decompose your conditional logic across multiple lines, which more closely resembles the pseudocode you would write out when planning an algorithm on paper. GDScript’s lack of braces to indicate indents (ie comparing to C-series languages) means there’s still a significant limit to that readability benefit, but in most cases it’s still easier for a human to parse that than a deep Excel formula.

The bigger reason to use nested if-statements is when you are dealing with multiple conditionals that, when evaluated together, create a truth table with more than 2 states. In that case, the well-planned use of nested if-statements will efficiently aggregate the different ways in which a given state can be reached so that you don’t need to write n! extended-conditional if-statements to cover every possibility, like trying every combination in the classic “multiple levers in a dungeon” puzzle.

The raycast camera code from Barbarian Blaster (making the GridMap clickable, changing the cursor, checking if there’s enough gold to place a turret, etc.) is a good example. Bram’s nest of if-statements can be simplified a little here and there, but I’m sure you can see, trying to completely replace nested if-statements with boolean operators in that situation would just create a mess. That’s because every true conditional along the way actually results in doing something (vs. just triggering the next if-statement), thereby creating a whole new state to handle in the system’s truth table.

That said, frequently an even better approach (works with the above example too) is checking a negative condition instead and breaking / continueing or returning from the nest if that returns true. Like job applications XD Not only does this drastically reduce indenting in big nests because you simplify your pending logic equation as you go, but it might be more performant as well for the same reason.

Thanks for raising the point. Writing all of this out actually gave me a much better understanding of it, which is awesome because I’m still learning just like everybody else here =)

2 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms