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

Python

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

B語言

putchar(col%50?' ': '*n'); } putchar('*n*n'); } v[2000]; n 2000; BCPL C語言 B - computer programming language. [2021-03-14]. (原始内容存档于2015-02-10).  Thompson, Ken. Users'

二分法 (數學)

Mathcad, Maple, Matlab, Mathematica True example of using bisection method in computer programming free program to isoelectric point calculation 介值定理

反射式编程

在计算机学中,反射式编程(英語:reflective programming)或反射(英語:reflection),是指计算机程序在运行时(runtime)可以访问、检测和修改它本身状态或行为的一种能力。用比喻来说,反射就是程序在运行的时候能够“观察”并且修改自己的行为。 要注意术语“反射”和“类型内省”(type

Common Lisp对象系统

标准方法组合中的这些辅助方法,对应于面向方面编程中的建议(英语:Advice (programming))。对比于在方面(英语:Aspect (computer programming))中规定当其他的类的指定名称方法被执行时触发建议的定点切入(英语:pointcut),CLOS的

OCaml

1985 [2021-09-03]. (原始内容存档于2021-09-03).  LNCS, 201, Functional programming languages computer architecture, pp.~50-64. Michel Mauny, Ascánder Suárez. Implementing

線性同餘方法

(10): 1192–1201. doi:10.1145/63039.63042.  D. E. Knuth. The Art of Computer Programming, Volume 2: Seminumerical Algorithms, Third Edition. Addison-Wesley

Ada

Programming Jan Skansholm:Ada 95 From the Beginning, Addison-Wesley, ISBN 0-201-40376-5 John Barnes(英语:John Barnes (computer scientist)):Programming in