9
0

More than 1 year has passed since last update.

early return(早期リターン)についてまとめる 可読性の上がるコーディング

Last updated at Posted at 2022-08-14

はじめに

early returnとはコーディングにおけるテクニック。

条件式を扱う際に早期にreturnを返すことでif文のネストを減らすというテクニック。

この記事でearly returnについてまとめていきます。

2022/08/14 21時50分 追記
※あくまでコーディングにおけるテクニックの一例を示すものです。こういうものがあるよ、ぐらいの認識で読んで頂ければ幸いです。

early returnでリファクタリング(修正前)

ここで一例を挙げてみる。

sample.py
class Student:

  def __init__(self, student_id, name):
    self.student_id = student_id
    self.name = name

  def student_check(self):
    
    if self.student_id != "" or self.name != "":
      if len(self.student_id) > 12:
        flg = False
      else:
        flg = True
    else:
      flg = False
    return flg

student_exe = Student("101122222212","山田花子")
student_exe.student_check()

このコーディングの中で可読性を落としているのは一例として、if文のネストが挙げられる。
今回は簡易的な処理しか書いていないが、、、

実際には条件式の後に多くの処理が書かれる訳で。。。

数十行も書いたソースコードをネストさせて、ネスト後にも数十行書かれていたとしたら、可読性はもっと落ちてくる。

そこでソースコードを改善する為にearly returnを使う。

2022/08/14 21時50分 追記分
そこで今回は記事の題名にもなっている、early returnを使ってコードを修正していく。
early returnは名前の通り、早期にreturnをすることである。

そもそも論として、returnは必ず関数の最後で使わなければならないのか?

答えはNoである。

勿論、常にearly returnを使うことが正解という訳ではない。
ただ、returnを必ず関数の最後に書くという思い込みを消すことが大事なのである。

early returnでリファクタリング(修正後)

sample.py
class Student:

  def __init__(self, student_id, name):
    self.student_id = student_id
    self.name = name

  def student_check(self):
    if self.student_id == "" or self.name == "" or len(self.student_id) <12:
      flg = False
      return flg
    if self.student_id != "" and len(self.student_id) >12:
      flg = True
      return flg
 
student_exe = Student("10112222222212","山田花子")
student_exe.student_check()

この様に途中でreturnを行うことでif文のネストを減らすことができる。
心なしか可読性が上がった気がしませんか?

色々と粗はあると思いますが。。。

最後に

early returnを意識して無駄なif文のネストを減らしましょう。

2022/08/14 21:50追記分
early returnを使えば、if文のネストを減らせることがあります。
※勿論、early returnをすれば必ずしも可読性が上がる訳ではないです。
なので、ここはearly returnを使った方が良いな、みたいな時に使ってみてください。

9
0
4

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