3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

条件分岐について(ネストの解消)

Last updated at Posted at 2023-06-28

目的

「良いコード/悪いコードで学ぶ設計入門」のアウトプット
 (6章 6.1 条件分岐のネストによる可読性低下)

早期return

入れ子構造が深くなると処理ブロック({}で括られた処理範囲)がどこからどこまでが分かりずらくなる。
複雑そうな処理の場合は、処理ブロックでifを対応するより早期returnで対応した方がネストを防げる。

元のif文
  function sample(){
    if ( 0 < $condA) { 
      if ( $condB ) {
        if ( $condC <= $condD ) {
          echo("Hello World");
        }
      }
    }
  }
早期return を使うと階層が浅くなる。
  function sample(){
    if ( $condA <= 0 ) return;  // 通常のif文から早期returnへ修正する場合は条件を逆にする。
    if ( $condB) {
      if ( $condC <= $condD ) {
        echo("Hello World");
      }
    }
  } 
他の条件にも早期returnを適応
  function sample(){
    if ( $condA <= 0 ) return;
    if ( !$condB ) return;
    if ( $condD < $condC ) return;
    echo("Hello World");
  }

早期returnを使って冒頭で条件を弾くようにすると見通しがよくなる。

メリット

条件ロジックと実行ロジックの分離

  // 条件ロジック
  if ( $condA <= 0 ) return;
  if ( !$condB ) return;
  if ( $condD < $condC ) return;

  // 実行ロジック
  echo("Hello World");

 

追加が容易

  // 条件ロジック
  if ( $condA <= 0 ) return;
  if ( !$condB ) return;
  if ( $condD < $condC ) return;
  if ( !$condE ) return;  // NEW!

  // 実行ロジック
  echo("Hello World");
  echo("GOOD!!");  // NEW!

早期retun(else句)

:元のif文
    function sample(){
      if ($condA) {
        $test = "Hello A";
      }elseif ($condB) {
        $test = "Hello B";
      }elseif ($condC) {
        $test = "Hello C";
      }elseif ($condD) {
        $test = "Hello D";
      }elseif ($condE) {
        $test = "Hello E";
      }else {
        $test = "another";  
      }
      return $test;
    }
見ずらいので各if文ブロックをreturnに置き換える。
  function sample(){
    if ($condA) {
      return "Hello A";
    }elseif ($condB) {
      return "Hello B";
    }elseif ($condC) {
      return "Hello C";
    }elseif ($condD) {
      return "Hello D";
    }elseif ($condE) {
      return "Hello E";
    }
  }
今回は条件に合致したらそのまま返す形にする
  function sample(){
    if ($condA) return "Hello A";
    if ($condB) return "Hello B";
    if ($condC) return "Hello C";
    if ($condD) return "Hello D";
    if ($condE) return "Hello E";
  }

参考文献

良いコード/悪いコードで学ぶ設計入門 ―保守しやすい 成長し続けるコードの書き方

感想

リファクタリングしているときにif文がネストして複雑になっているとコードブロックがどこがどこまでの範囲が分からなくなっているので、三項演算子とか組み合わせてなるべく短くしたい。
しかし短くしすぎると今度は可読性が低下する。保守しやすいように直さないといけないのでバランスが難しい。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?