if Statements Should Stand Alone
The Core Philosophy
This rule is a direct extension of the Single Responsibility Principle.
- Doing work is one thing.
- Checking a condition is another thing.
If your function performs some calculations (work) and then checks a condition (logic), it is effectively doing two things. To fix this, the function should be split so that the conditional check stands alone as the "gatekeeper."
The Rule in Detail
- First Thing: No variable declarations, print statements, or calculations should exist before the
if. - Only Thing: Ideally, nothing should happen after the
if/elseblock either. The function exists solely to decide which path to take.
We do not necessarily need to extract the body of the if statement immediately (unless it violates length rules), because the if/else structure itself is a single unit of logic. We rely on this structure to guide readability.
C# Examples
❌ The "Mixed Concerns" Approach (Bad)
This method does setup work and makes a decision. It violates the rule because the if is not the first statement.
✅ The "Gatekeeper" Approach (Good)
To fix this, we extract the setup work into a previous step. The ProcessOrder method now strictly acts as a decision handler.
Conclusion
By forcing if statements to the top, you naturally separate logic (making decisions) from execution (doing the work). This makes your code structure obvious at a glance: a method either does something, or it decides something—never both.