1
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?

More than 1 year has passed since last update.

早期リターンって,値を返す関数しか考えてない?

Posted at

タイトル通り「早期リターンって,値を返す関数しか考えてない?」

初心者入門のプログラム FizzBuzz。回答例は以下のようなものですよね(Python)。

def fizzbuzz(i):
    if i % 3 == 0 and i % 5 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

これを,「早期リターン」で書くと,とてもみっともないプログラムになります。
読みやすいですか? 保守性が高いですか? メリットは何?

def fizzbuzz(i):
    if i % 3 == 0 and i % 5 == 0:
        print("FizzBuzz")
        return

    if i % 3 == 0:
        print("Fizz")
        return

    if i % 5 == 0:
        print("Buzz")
        return 
    
    print(i)

んっなわけないですよね。

そもそも,「ネストが深いダメダメプログラム」ってのは,例えば

def fizzbuzz(i):
    if i % 15 == 0:
        if i % 3 == 0 and i % 5 == 0:
            print("FizzBuzz")
        elif i % 3 == 0:
            print("Fizz")
        else:
            print("Buzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

こんなプログラム書いたら,そもそも,怒られます。

1
0
1

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
1
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?