跳至內容

詛咒金字塔 (編程)

維基百科,自由的百科全書

計算機編程中,詛咒金字塔(pyramid of doom)是一種常見編碼風格——程序用多層嵌套的縮進來訪問一個功能。常見於檢查空指針或處理回調函數[1]

例子[編輯]

大多數現代物件導向程式語言使用點表示法,允許單行代碼中的多層方法調用,每一層方法調用用點來分割。例如:[2]

theWidth = windows("Main").views(5).size().width();

這段代碼首先在windows集合中找到一個名字為"Main"的窗體,再找到窗體的views集合中第5個subview,調用其size方法,返回的結構中再調用width方法,結果最後賦值給變量名theWidth

上述代碼存在的問題是需要假定所有這些值都存在。如果這個假設不成立,則會遇到空指針錯誤。

為避免這類問題,一般在每層方法調用都要檢查其返回值。一個更為安全的編碼為:

if windows.contains("Main") {
    if windows("Main").views.contains(5) {
        theWidth = windows("Main").views(5).size().width();
        //more code that works with theWidth
    }
}

如果還想檢查值是否存在、是否有效,if語句中的代碼就會越來越靠右,使得閱讀代碼更為困難。一些讓代碼扁平化的方法被提了出來:

if windows.contains("Main") { theWindow = windows("Main") }
if theWindow != null && theWindow.views.contains(5) { theView = theWindow.views(5) }
if theView != null {
    theWidth = theView.size().width();
    //additional code
}

或者:

if !windows.contains("Main") {
    // handle error
} else if !windows("Main").views.contains(5) {
    // handle error
} else {
    theWidth = windows("Main").views(5).size().width();
    //more code that works with theWidth
}

很多程式語言為此提供了一些語法糖來解決這類問題。例如Apple的Swift語言在if語句中增加了optional chaining[3]。微軟的C# 6.0和Visual Basic 14增加了null-conditional運算符?.?[分別用於成員訪問和下標訪問。[4][5][6]基本想法是訪問空對象的成員時直接返回空值,例如:[7][8]

theWidth = windows("Main")?.views(5)?.size.width;

如果"Main"或第五個subview缺失,整個值為空。Swift語言增加了if let語句,即"optional binding":

if let theView = windows("Main")?.views(5) {
    //do things knowing the view exists...
    theWidth = theView.size.width
}

參見[編輯]

參考文獻[編輯]

  1. ^ Dave Herman. Why coroutines won't work on the web. The Little Calculist. 14 December 2011. (原始內容存檔於2016-03-06). 
  2. ^ The Pyramid of Doom: A javaScript Style Trap. 27 November 2012. (原始內容存檔於2015-12-09). 
  3. ^ Optional Chaining. Apple. [2022-03-01]. (原始內容存檔於2016-03-25). 
  4. ^ Null-conditional Operators (C# and Visual Basic). Microsoft. [2022-03-01]. (原始內容存檔於2016-06-23). 
  5. ^ What's New for Visual C#. Microsoft. [2022-03-01]. (原始內容存檔於2017-04-03). 
  6. ^ What's New for Visual Basic. Microsoft. [2022-03-01]. (原始內容存檔於2016-11-17). 
  7. ^ Eberhardt, Colin. Tearing Down Swift's Optional Pyramid Of Doom. 8 December 2014. (原始內容存檔於2016-07-31). 
  8. ^ New Language Features in Visual Basic 14. 9 December 2014. (原始內容存檔於2014-12-25). 
  9. ^ Joe Zimmerman. What's The Point Of Promises?. telerik.com. March 28, 2013 [2022-03-01]. (原始內容存檔於2022-04-06).