Single State Handling
Descriptionβ
What does it look like?β
- Object behavior varies by internal state, but state and behavior are tightly coupled
- State-specific behavior is managed using
if
orswitch
statements - As states increase, the logic bloats and becomes harder to read
Why is it a problem?β
- Each new state requires modifying existing code (violates the Open/Closed Principle)
- Responsibilities are concentrated in a single class, leading to low readability and difficult testing
- Future expansions and state transition logic become complex and error-prone
Bad Example of the Anti-patternβ
- TypeScript
- PHP
- Python
class Document {
private state: string = "draft"; // ηΆζ
: 'draft', 'review', 'published'
publish() {
if (this.state === "draft") {
console.log("γ¬γγ₯γΌδΎι ΌγιδΏ‘");
this.state = "review";
} else if (this.state === "review") {
console.log("ε
¬ιγγΎγγ");
this.state = "published";
} else if (this.state === "published") {
console.log("γγ§γ«ε
¬ιζΈγΏγ§γ");
}
}
}
<?php
class Document {
private string $state = "draft"; // ηΆζ
: 'draft', 'review', 'published'
public function publish(): void {
if ($this->state === "draft") {
echo "γ¬γγ₯γΌδΎι ΌγιδΏ‘\n";
$this->state = "review";
} elseif ($this->state === "review") {
echo "ε
¬ιγγΎγγ\n";
$this->state = "published";
} elseif ($this->state === "published") {
echo "γγ§γ«ε
¬ιζΈγΏγ§γ\n";
}
}
}
class Document:
def __init__(self):
self.state = "draft" # ηΆζ
: 'draft', 'review', 'published'
def publish(self):
if self.state == "draft":
print("γ¬γγ₯γΌδΎι ΌγιδΏ‘")
self.state = "review"
elif self.state == "review":
print("ε
¬ιγγΎγγ")
self.state = "published"
elif self.state == "published":
print("γγ§γ«ε
¬ιζΈγΏγ§γ")
Issues:β
- State is managed as a plain string, and behavior is centralized in a single method
- Whenever a new state is added,
publish()
must be modified - Mixing state and logic in one place makes the design fragile and hard to extend
Refactoring by Patternβ
Design patterns that can address thisβ
Pattern | Overview | Main Refactoring Approach |
---|---|---|
State | Separate objects by state and delegate behavior | Manage state explicitly using classes |
Strategy | Replace behavior externally | Let external context control state switching |
Command | Encapsulate state-specific actions as command objects | Represent behavior as objects for flexibility |