0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[審美眼を鍛えようシリーズ] 分岐を省略しない

0
Last updated at Posted at 2026-08-28
Page 1 of 9

分岐とは

  • if - else
  • switch
  • case   など

言うまでもなく、条件によって処理を変える、どんなプログラムにも備わっている機能


今日の主張

  • ifを書いたらelseを省略しない
  • switchを書いたらdefaultを省略しない
  • 全ての選択肢を吟味する

手続き型言語は分岐を省略できる

if (enabled) {
    ...
}

しかし、省略しない方がよい

if (enabled) {
    ...
} else {
    // 処理なし
}

省略しないことの効果

想定外ケースを考える機会になる


組み合わせて欲しいプラクティス

  • 常に戻り値を返すようにする

手続き型の苦悩

  • ifやswitchが文
  • 三項演算子をうまく使いたい
  • 関数化もよい:値を返さないパスが残っていることを教えてくれる
var res = enabled
    ? doProcEnabled() 
    : doProcDisabled()
    ;

ちょっと脱線:文と式の違い

  • 文は値を返さない
  • 式は評価結果が値
  • 式だけでプログラムを作るスタイルは堅牢(値を返さないとエラーになるため)
  • 関数型プログラミング言語はこの思想で設計されている

最後に

  • 全ケースを本気で網羅できるのはプログラマだけ

  • 抜け漏れを防ぐには分岐を省略せずに考える

  • 設計も同じ。「こちらがこうなら、あちらはどうなる?」の思考が大事

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?