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

外部链接

编辑

📚 Artikel Terkait di Wikipedia

函数式编程

函数式编程,或称函数程序设计、泛函编程(英語:Functional programming),是一种编程范型,它将电脑运算视为函数运算,并且避免使用程式状态(英语:State (computer science))以及可變物件。 在函数式编程中,函数是头等对象即头等函数,这意味着一个函数,既可以作

宣告式編程

Coenen. Characteristics of declarative programming languages. 1999. Robert Harper(英语:Robert Harper (computer scientist)). What, If Anything, Is A Declarative

Python

this(英语:this (computer programming))关键字,Python的对象方法沿袭自Modula-3,使用显式的第一个形式参数来访问实例特性,习惯上将其命名为self(英语:this (computer programming))。

编程语言

编程语言(英語:programming language)是用来表達计算机程序的電腦語言。它是一套标准化的交流技巧,一种能够让程序员准确地定义计算机所需数据的语言,以向计算机发出指令并精确地定义不同情况下应当采取的行动。 最早的编程语言早在電腦發明前就已問世,當時是用來控制提花織布機(英语:Jacquard

BCPL

BCPL - a tool for compiler writing and systems programming (Proceedings of the Spring Joint Computer Conference, Vol 34, pp 557-566, 1969) Martin Richards

KornShell

KornShell(ksh)是一款由大卫·科恩(英语:David Korn (computer scientist))于二十世纪八十年代早期在贝尔实验室开发的Unix shell,并在1983年7月14日的USENIX年度技术会议(英语:USENIX Annual Technical

计算机程序的构造和解释

illusion that this is a text digestible at MIT only, peculiar to the breed found there. It is precisely what a serious book on programming Lisp must be

面向切面的程序设计

面向方面编程的核心概念,是从核心关注中分离出交叉切入关注。面向方面编程,在支配性分解的基础上,提供叫做方面(英语:Aspect (computer programming))(aspect)的一种辅助的模块化机制,这种新的模块化机制可以捕捉交叉切入关注。 面向方面编程语言的建议相关构件,定义了一个接