方法鏈式呼叫

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

方法鏈式呼叫(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. 

外部連結[編輯]