方法链式调用

本页使用了标题或全文手工转换
维基百科,自由的百科全书

方法链式调用(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. 

外部链接