7

近道ではなく、複数のブロックに足を踏み入れることを好む特定の理由はありますか? たとえば、複数の条件が評価される次の 2 つの関数を考えてみましょう。最初の例は各ブロックにステップインするもので、2 番目の例はショートカットです。例は Python で書かれていますが、質問は Python に限定されません。それも過度に矮小化されています。

def some_function():
    if some_condition:
        if some_other_condition:
            do_something()

対。

def some_function():
    if not some_condition:
        return
    it not some_other_condition:
        return
    do_something()
4

1 に答える 1

7

2 番目を優先すると、コードが読みやすくなります。あなたの例ではそれほど明白ではありませんが、次のことを考慮してください。

def some_function()
    if not some_condition:
       return 1
    if not some_other_condition:
       return 2
    do_something()
    return 0

def some_function():
    if some_condition:
       if some_other_condition:
           do_something()
           return 0
       else:
           return 2
    else:
        return 1

関数が「失敗」状態の戻り値を持たない場合でも、逆の ifs 方法で関数を記述すると、ブレークポイントの配置とデバッグが容易になります。元の例では、 some_condition または some_other_condition が失敗したためにコードが実行されていないかどうかを知りたい場合、ブレークポイントをどこに配置しますか?

于 2012-11-28T03:43:21.823 に答える