Appearance
条件分岐の設計 ― ネストが深くなったら
この章のキーワード
| 用語 | 意味 | なぜ重要か |
|---|---|---|
| match 式 | PHP 8+ の条件分岐構文 | 各条件タイプを個別メソッドに分離しやすい |
| 複合条件(AND/OR) | 複数条件を論理演算で組み合わせる | ネストが深いとテスト困難 |
| JSON 設定駆動 | 条件をコードではなく JSON データで定義する設計 | マイグレーション不要で柔軟だが暗黙的 |
| 組み合わせ爆発 | 条件のネストにより評価パスが指数的に増加する現象 | テストカバレッジの限界 |
Phase 1: 観察
exemplar 条件分岐の設計パターンとして、参考になる実装です。
LIBOT のシナリオエンジンは、ユーザーの状態に応じて異なるアクションを実行します。 その条件評価ロジックを見てみましょう。
php
// ScenarioConditionService.php (excerpt)
// Label: exemplar
public function check($step, $friend, $previousDelivery): array
{
$type = $step->condition_type;
// match 式で条件タイプごとに処理を分岐
$result = match ($type) {
Constant::STEP_CONDITION_TYPE_NONE => true,
Constant::STEP_CONDITION_TYPE_TAG => $this->checkTagCondition($step, $friend),
Constant::STEP_CONDITION_TYPE_SURVEY => $this->checkSurveyCondition($step, $friend),
Constant::STEP_CONDITION_TYPE_CLICK => $this->checkClickCondition($step, $previousDelivery),
Constant::STEP_CONDITION_TYPE_OPEN => $this->checkOpenCondition($step, $previousDelivery),
Constant::STEP_CONDITION_TYPE_POINT => $this->checkPointCondition($step, $friend),
Constant::STEP_CONDITION_TYPE_REFERRAL => $this->checkReferralCondition($step, $friend),
Constant::STEP_CONDITION_TYPE_COMPOUND => $this->checkCompoundCondition($step, $friend),
default => true,
};
return ['result' => $result, /* ... */];
}さらに、複合条件(AND/OR)の評価:
php
// 複合条件の評価
private function checkCompoundCondition($step, $friend): bool
{
$config = $step->condition_config;
$logic = $config['logic'] ?? 'and'; // "and" または "or"
$conditions = $config['conditions'] ?? [];
foreach ($conditions as $condition) {
$result = $this->evaluateSingleCondition($condition, $friend);
if ($logic === 'or' && $result) return true; // OR: 1つでも真なら真
if ($logic === 'and' && !$result) return false; // AND: 1つでも偽なら偽
}
return $logic === 'and'; // AND: 全て真なら真、OR: 全て偽なら偽
}Phase 2: 判断
AI禁止ゾーン
match式で 8 種類の条件を分岐しています。9 種類目を追加する とき、何をどう変えますか?- AND/OR の複合条件が 10 段ネスト したら、何が起きますか?
- 条件を JSON 設定 で管理するメリットとデメリットは何ですか?
AIに聞く前に、自分の頭で考えてみましょう。
テキストを入力すると有効になります