D
11

TIL I'd been nesting if statements completely backwards for 2 years

I was building a login system for a school project back in March and kept getting errors when users had the right password but wrong username. Spent 3 hours staring at my code before my buddy Mike glanced at it and said 'why are you checking the inner condition first?' I had been nesting my conditions from the most specific to the most general, so the code would fail on the first check and never reach the broader validations. Mike showed me to put the broad checks on the outside and work inward. Felt like an idiot but at least I learned something. Has anyone else had a moment where a simple pattern like nesting order clicked for them way later than it should have?
2 comments

Log in to join the discussion

Log In
2 Comments
loganburns
loganburns1mo ago
Used to think nesting was just a style thing until I ran into the same problem with a checkout system. Had all the specific checks like "is the coupon code valid" nested deep inside broader ones and it just broke everything. What clicked for me was realizing the outer condition acts like a gate that the inner stuff never reaches if it fails first. Kinda obvious looking back but man did I feel dumb when my roommate pointed it out after I'd been wrestling with it for an evening.
6
patriciam22
Yeah but here's what I still don't get. When you finally flip it around and put the broad checks on the outside, does that ever mess with how you structure your error messages? Like if a user fails the outer gate, do you just give them a generic "something's wrong" or do you try to figure out which specific inner condition failed first? Cause I swear every time I restructure my nesting I end up with error handling that's either too vague or too detailed to be useful.
-1