2012-11-28 33 views
4

是否有一個特別的理由來支持步入多個塊與短切?例如,採用以下兩種評估多個條件的功能。第一個例子是進入每個塊,而第二個例子是快捷方式。這些例子是用Python編寫的,但問題不僅限於Python。它也過分瑣碎。倒立的if語句

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() 
+0

因爲第二個有時看起來更漂亮嗎? – Xymostech

+0

我的許多教授會贊成前者。在函數/方法的中間,他們並沒有因爲回報而失望。 http://stackoverflow.com/questions/4838828/why-should-a-function-have-only-one-exit-point – austin

回答

4

利於第二使代碼更易於閱讀。這不是在你的例子是明顯的,但是考慮:

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

VS

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

即使函數爲「失敗」的條件沒有返回值,寫第二種方式使得設置斷點的功能和調試更容易。 在你最初的例子中,如果你想知道你的代碼是不是運行的,因爲some_condition或some_other_condition失敗了,你會在哪裏放置斷點?