メインコンテンツまでスキップ

複雑な手順の露出

説明(どんな問題か)

どんな状態か?

  • 呼び出し元が、複雑な処理をすべて直接実行している
  • 複数のコンポーネントを毎回組み合わせて使っており、呼び出しコードが煩雑
  • 何をしているのか全体の意図が見えづらい

なぜ問題か?

  • 同じ複雑な処理が何度も書かれてしまう
  • 修正が必要になったとき、すべての呼び出し箇所に波及
  • 呼び出し側の責務が増えすぎて、責任の分離ができていない

アンチパターンのコード例

class AuthService {
authenticate(userId: string): boolean {
console.log(`ユーザー認証: ${userId}`);
return true;
}
}

class UserProfileService {
load(userId: string): object {
console.log(`プロフィール取得: ${userId}`);
return { name: "Hiroshi", id: userId };
}
}

class AuditService {
log(action: string) {
console.log(`[監査ログ] ${action}`);
}
}

// 呼び出し元が全部自分で処理を組み立てている
function showUserProfile(userId: string) {
const auth = new AuthService();
const profileService = new UserProfileService();
const audit = new AuditService();

if (auth.authenticate(userId)) {
const profile = profileService.load(userId);
console.log(profile);
audit.log("プロフィール表示");
}
}

️ 問題点:

  • 呼び出し元が 3 つのクラスを組み合わせて制御しており、複雑な手順が露出
  • 認証・データ取得・監査ログが呼び出し側にべったり
  • 同じ処理を他でもやる場合、コードが重複・煩雑

パターン別のリファクタリング

対応可能なデザインパターン例

パターン概要主な解決アプローチ
Facade複雑な処理をまとめた窓口を提供処理の呼び出しを簡潔に統一できる
Proxy呼び出しを仲介して処理を追加・制御キャッシュ、認証、遅延実行などに対応
Iterator集合や構造を安全に走査する手段を提供複雑な繰り返し処理のカプセル化・統一が可能に