Spaghetti Code
Unstructured control flow that is hard to follow.
“A bowl of spaghetti is a tangled mess. So is this code.” – Brown et al.
Code with complex and tangled control structure.
Signs of Use (Symptoms)
- Control flow jumps around unpredictably (GOTOs, extensive use of exceptions for flow).
- No clear separation of concerns; everything interacts with everything.
- Deeply nested conditionals and loops that are hard to unwind.
Why it is bad (Consequences)
- Readability: Impossible to read linearly.
- Maintainability: Changing one part breaks another due to hidden connections.
- Reusability: Code is too tangled to extract useful parts.
Why it happens (Root Cause)
Lack of planning, experience, or discipline. “Just getting it to work” without refactoring.
When it might be okay (Exceptions)
- Small, isolated scripts (under 50 lines).
- Generated state machine code (not meant for humans).
Explanation
Problem
A feature needed to be added quickly, then another, then another. The original structure wasn’t updated.
The Flaw
Structure is sacrificed for speed. The code becomes a “Big Ball of Mud”.
Real world analogy
A physical bowl of spaghetti. You pull on one noodle, and the whole pile moves.
Refactoring Solution
- Extract Method: Group related logic into functions.
- Decompose Conditional: Simplify complex checks.
- Replace Conditional with Polymorphism.
Pros and Cons (of the Antipattern)
| Pros (Why people do it) | Cons (The price you pay) |
|---|---|
Comparison
- Related Antipatterns: The Blob (Large Class).
- Related Principles: Separation of Concerns, KISS.
Code example
Typescript
Bad (The Antipattern)
Good (The Fix)
PHP
Bad (The Antipattern)
Good (The Fix)