履歴の欠如
説明(どんな問題か)
どんな状態か?
- ユーザーの操作履歴を保存していないため、操作の取り消し(Undo)ややり直し(Redo)ができない
- 処理の副作用を元に戻す手段がない
- 履歴がないため、状態の復元や巻き戻しが難しい
なぜ問題か?
- ユーザー体験(UX)の低下(戻る機能がない)
- 操作ミスのリカバリができず、再入力や復元作業が必要
- 複雑な状態操作でのバグ修正や調査が困難
アンチパターンのコード例
- TypeScript
- PHP
- Python
class TextEditor {
private content: string = "";
type(text: string) {
this.content += text;
}
getContent() {
return this.content;
}
}
const editor = new TextEditor();
editor.type("Hello ");
editor.type("World");
console.log(editor.getContent()); // Hello World
// 取り消しができない!
<?php
class TextEditor {
private string $content = "";
public function type(string $text): void {
$this->content .= $text;
}
public function getContent(): string {
return $this->content;
}
}
// 利用例
$editor = new TextEditor();
$editor->type("Hello ");
$editor->type("World");
echo $editor->getContent(); // Hello World
// 取り消しができない!
class TextEditor:
def __init__(self):
self.content = ""
def type(self, text: str):
self.content += text
def get_content(self) -> str:
return self.content
# 利用例
editor = TextEditor()
editor.type("Hello ")
editor.type("World")
print(editor.get_content()) # Hello World
# 取り消しができない!
問題点:
- 入力操作をそのまま状態に反映しており、元に戻す手段がない
type()
が直接状態を変更するため、履歴の管理も困難
パターン別のリファクタリング
対応可能なデザインパターン例
パターン | 概要 | 主な解決アプローチ |
---|---|---|
Command | 処理を「命令オブジェクト」として表現し、実行・取消・再実行を管理 | 操作履歴を保存・実行・巻き戻し |
Memento | オブジェクトの状態をスナップショットとして保存・復元 | 状態の完全な記録と復元を実現 |