# Skill 04 - Control Flow, Pattern Matching, and Exceptions ## Selection and Iteration - Use `if` for simple decisions. - Use `switch` expressions for mapping values to results. - Use pattern matching for type, property, relational, and logical shape checks. - Use `foreach` for enumerating collections unless an index is required. - Use `for` when index control matters. - Avoid deeply nested conditionals; use guard clauses and extract methods. ## Guard Clause Rules - Validate public method parameters at the top. - Return early for invalid or no-op states when it reduces nesting. - Throw argument exceptions for invalid caller input. - Throw invalid operation exceptions for invalid object state. ## Exception Rules - Exceptions are for exceptional or invalid states, not normal branching. - Preserve stack traces. Use `throw;` when rethrowing inside a catch block. - Add context when wrapping exceptions. - Do not catch broad exceptions unless the boundary can recover, log, translate, or shut down cleanly. - Do not expose sensitive details in web responses. ## Overflow and Defensive Coding - Use `checked` where overflow would corrupt calculations. - Validate external input before conversion or persistence. - Prefer result objects for expected validation outcomes and exceptions for programming/runtime failures.