热门问题
时间线
聊天
视角

詛咒金字塔 (編程)

来自维基百科,自由的百科全书

Remove ads

計算機編程中,詛咒金字塔(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
}
Remove ads

參見

參考文獻

Loading related searches...

Wikiwand - on

Seamless Wikipedia browsing. On steroids.

Remove ads