Method Chaining, Postfix Operator, and OOP

By Xah Lee. Date: . Last updated: .
  1. in JavaScript, there's method chaining x.f.g. its extremely convenient, widely loved, in ruby too. ♥ ♥ ♥
  2. however, there's a troublesome aspect, namely, object and properties.
  3. method chaining relies on object properties to work, which is a semantic issue.
  4. in most languages there's no postfix operator.
  5. To chain functions, f must return a object and that object must have next f as property.
  6. then, you use the dot notation for property access, to achieve method chaining.
  7. the problem with this is that we rely on a semantic property for its side effect of syntactic convenience.
  8. if dot notation doesn't exist in js, then x.f(a).g(b) is written as x[f](a)[g](b). Would you still want to chain?
  9. as a practical example, in js, if f g are functions and their return value are not objects, you cannot chain them, as in x.f.g
  10. to be able to chain arbitrary functions, you need a postfix operator. unix pipe x|f|g, Wolfram Language x//f//g

Note: a related concept is function composition. It has somewhat the same purpose of postfix operator with respect to syntax convenience. Because, it avoids nesting, and lets you write sequential application of functions in a sequential manner. [see What's Function, What's Operator?]

In lisp language that doesn't use operators, function composition is the natural solution. For example, in Clojure, it's called “threading”. [see Clojure: Function Chaining]

in JavaScript and many other languages, if the language doesn't have postfix notation, one can make-do by defining a pipe function.

[see JS: Pipe Function Instead of Method Chaining]

Unix Pipe, Dot Notation, Postfix Notation

  1. OOP Dot Notation, Dot Before Data or After?
  2. OOP Dot Notation, is Object Data or Namespace?
  3. Unix Pipe as Functional Language
  4. Method Chaining, Postfix Operator, and OOP
  5. JavaScript Language Design: Dot Notation be Namespace or Object System
  6. Ontology of Postfix Notation, Method Chaining, and Unix Pipe
  7. Piping and Function Composition Equivalence

If you have a question, put $5 at patreon and message me.