跳至內容

方法鏈式調用

本頁使用了標題或全文手工轉換
維基百科,自由的百科全書

方法鏈式調用(Method chaining),也稱為命名參數慣用法(named parameter idiom),是面向對象編程語言中多個方法被調用時的常用語法。每個方法都返回一個對象,允許在單個語句中將調用鏈接在一起,而無需變量來存儲中間結果。[1]

方法鏈式調用是一種語法糖[2]

類似的語法是方法級聯調用,即調用一個對象的多個方法的語法糖。方法級聯調用可以使用方法鏈式調用來實現,即讓每個方法返回當前對象本身英語this (computer programming)(this)。方法級聯調用是流暢接口的一項關鍵技術,面向對象語言廣泛實現了方法鏈式調用,但實現了方法級聯調用的不多。鏈式和級聯調用都來自 Smalltalk語言

雖然方法鏈式調用是語法,但它具有語義後果,即需要方法返回一個對象;如果通過方法鏈式調用實現級聯,這必須是當前對象本身英語this (computer programming)。 這可以防止返回值被用於其他目的,例如返回錯誤值英語error value

例子[編輯]

一個常見例子是C++標準模板庫中的iostream,其中運算符<<返回左參數對象,因此允許鏈式調用:

比較:

a << b << c;

等價於:

a << b;
a << c;

另一個例子是JavaScript使用內建的數組方法:

somethings
  .filter(x => x.count > 10)
  .sort((a, b) => a.count - b.count)
  .map(x => x.name)

參見[編輯]

參考文獻[編輯]

  1. ^ Applying Method Chaining. First Class Thoughts. [2011-04-13]. (原始內容存檔於2011-02-22). In order to simplify repeated object interactions on the same object the old trick Method Chaining originating the world of Smalltalk should be enforced. The idea is to let methods return this rather than void, thus affecting especially set() and add() methods. Method chaining arose during the designers of Smalltalk pursuit to minimize the number of keywords in the language, which lead to the discovery that void is an unnecessary keyword!. 
  2. ^ Martin, Robert Cecil. Clean Code: A Handbook of Agile Software Craftsmanship. Prentice Hall. 2008. ISBN 0-13-235088-2. 

外部連結[編輯]