Skip to main content

Method Cascades in Dart

Posted by Gilad Bracha

(UPDATE: Method cascades are now implemented.)

The idea of a cascaded method invocation originates in Smalltalk, and has been proposed for Dart.  The motivation is to make it easier to write more fluent interfaces. 

Usually, fluent interfaces rely on method chaining. Say you want to add a large number of elements to a table:

myTokenTable.add("aToken");
myTokenTable.add("anotherToken");
// many lines elided here
// and here 
// and on and on
myTokenTable.add("theUmpteenthToken");

You might want to write this as

myTokenTable.add("aToken")
            .add("anotherToken").  
            // many lines elided here
            // and here 
            // and on and on
            .add("theUmpteenthToken");

but this requires that add() return the receiver, myTokenTable, instead of the element you just added. The API designer has to plan for this, and it may conflict with other use cases. With cascades, no one needs to plan ahead or make this sort of tradeoff.  The add() method can do its usual thing and return its arguments. However, you can get a chaining effect using cascades:

myTokenTable
  ..add("aToken");
  ..add("anotherToken");
// many lines elided here
// and here 
// and on and on
  ..add("theUmpteenthToken");


Here, ".." is the cascaded method invocation operation.  The ".." syntax invokes a method (or setter or getter) but discards the result, and returns the original receiver instead.

In brief, method cascades provide a syntactic sugar for situations where the receiver of a method invocation might otherwise have to be repeated. Instead of writing:


var address = getAddress();
address.setStreet(“Elm”, “13a”);
address.city = “Carthage”;
address.state = “Eurasia”
address.zip(66666, extended: 6666);

One may write

getAddress()
 ..setStreet(“Elm”, “13a”)
 ..city = “Carthage”
 ..state = “Eurasia”
 ..zip(66666, extended: 6666);


The sugar pays off the more complex the API, the longer the receiver of the cascaded method invocations, and the more methods are being directed toward that receiver. Cascades are expressions, so they also compose better than statements.  A cascade always evaluates to its initial receiver (the details are in the draft specification at the end of this document).

Below you'll find a number of examples, and a draft specification. As always, feedback is welcome. However, I'm about to go on vacation - so don't be offended if it takes a while before I respond to any of your comments.

Examples


The examples below show the use of the construct using a couple of indentation styles. All styles place cascaded access on a separate line, which improves readability.

Example 1


Consider using a (modified) String API:

String s = (new StringBuffer()
..add('Jenny ')
..add('I ')
..add('got ')
..add('your ')
..add('number')
).toString();


Example 2


Another common example would be using a builder API

final addressBook = (new AddressBookBuilder()
..name = 'jenny'
..email = 'jenny867@aol.com'
..phone = (new PhoneNumberBuilder()
  ..number = '867-5309'
  ..label = 'home'
 ).build()
).build();


Example 3



class Point {
num x;
num y;

Point() {
  x = 0;
  y = 0;
}
void scale(num factor) {
 x *= factor;
 y *= factor;
}

// Hack to display debugging output while within a cascade. Naturally you can't use
// the regular print statement.
void log(String msg) {
 print ('logged ($x, $y): $msg');
 }

}

void main(){

num x = 10;
num y = 42; // not used
var p = new Point();
p..log('start')
 ..x = x
 ..scale(10)
 ..log('scaled')
 ..x++
 ..y = x + p.x + p.y;
print('p.x = ${p.x}, p.y = ${p.y}. x = $x');
}



Output:


logged (0, 0): start
logged (100, 0): scaled
p.x = 101, p.y = 111, x = 10




Example 4


class Node {
String key;
Node(this.key);
Node left;
Node right;
}


void main() {
Node right = new Node('e');
Node root = new Node('root')
 ..left = (new Node('a')
   ..left = (new Node('b')
     ..left = new Node('c')
     )
     ..right = Node('d')
 )
 ..right = right;
print(root);
}



Example 5

The following example is perhaps more typical of what you might do in a web application.

var dq = document.query('#mypanel').queryAll('TABLE .firstCol');
dq.classes.remove('firstCol');
dq.style
  ..background = 'red'
  ..border = '2px solid black'
;
dq.nodes.add(new Element.html('<span>This cell is now red</span>')) // ?
;

It might be even nicer if cascades nested, but the nesting makes things hard to read. 


document.query('#mypanel').queryAll('TABLE .firstCol')
..classes.remove('firstCol');
..(style
   ..background = 'red'
   ..border = '2px solid black'
) ..nodes.add(new Element.html('<span>This cell is now red</span>')) // Not legal, just an idea for nesting

Maybe in the future we'll find a way to support such nesting in a truly readable way. For now we defer the issue and stick with one level of cascading.




Example 6



var dq = document.query('#myTable');
var qfc = dq.queryAll('.firstColumn');
qfc.style
   ..background = 'red'
   ..border = '2px solid black'
  ;
qfc.text = 'first column';

dq.queryAll('.lastColumn')
  ..style.background = 'blue'
  ..text = 'last column';


Example 7


view.node.style
..position = 'absolute'
..left = '${_measuredLeft}px'
..top = '${_measuredTop}px'
..width = '${_measuredWidth}px'
..height = '${_measuredHeight}px'
..zIndex = '${layoutParams.layer}'
;



Example 8


front
..beginPath()
..fillStyle = penColor
..arc(tx, ty, penWidth/2+2, 0, PI2, true)
..fill()
..moveTo(wx, wy)
..strokeStyle = "black"
..lineTo(tx, ty)
..closePath()
..stroke()
;




Example 9


document.queryAll('myDiv')
        ..classes.remove('off') // ?
        ..classes.add('on') // ?
;





Example 10

Array access works as well


element.attributes
      ..['foo'] = bar
      ..['baz'] = bla
;



Specification



Here is an initial take on the specification for this proposal. Places where the current spec changes are highlighted in yellow.

A cascaded method invocation has the form e..suffix

where suffix is a sequence of operator, method, getter or setter invocations.

A cascaded method invocation expression of the form e..suffix is equivalent to the expression (t){t.suffix; return t;}(e).


Grammar Changes



topLevelExpression:      assignableExpression assignmentOperator cascade
   | conditionalExpression ('..' cascadeSection)*
   ;


primary:      thisExpression    | super assignableSelector
   | functionExpression
   | literal
   | identifier
   | newExpression
   | constantObjectExpression
   |
'(' topLevelExpression ')'    ;


cascadeSection:     (assignableSelector arguments*)+ (assignmentOperator expression)?
   ;

Popular posts from this blog

AngularDart 4

AngularDart v4 is now available. We've been busy since the release angular2 v3.1.0 in May. Not only did we "drop the 2", but we also improved the compiler and tightened up the framework to give you smaller code, we updated the package structure to improve usability, and we added several new features. Check out the updated documentation to get started.
Just angular Upgrading to v4 will require more than updating your version constraint. The package has changed names (back) to angular – dropping the 2. You'll need to update your pubspec.yaml and the corresponding imports in your code. In most instances, find-and-replace should do the trick. Going forward, the package will be called package:angular. We'll just update the version number.
Smaller code The updated compiler in 4.0 allows type-based optimizations that not only improve runtime performance but generate better code because we are able to strongly type templates. A big result of the update is that many ap…

The new AdWords UI uses Dart — we asked why

Google just announced a re-designed AdWords experience. In case you’re not familiar with AdWords: businesses use it to advertise on google.com and partner websites. Advertising makes up majority of Google’s revenue, so when Google decides to completely redo the customer-facing front end to it, it’s a big deal. The Dart team is proud to say that this new front end is built with Dart and Angular 2. Whenever you asked us whether Google is ‘even using Dart for anything,’ this is what we had in mind but couldn’t say aloud. Until now. We asked Joshy Joseph, the primary technical lead on the project, some questions. Joshy is focusing on things like infrastructure, application latency and development velocity, so he’s the right person to ask about Dart.Q: What exactly did we launch on Monday?It’s a complete redesign of the AdWords customer experience that is rolling out slowly as a test to a small initial set of advertisers. The most noticeable thing is probably the Material Design look and f…

Const, Static, Final, Oh my!

Posted by Seth Ladd

(This is an "oldie but a goodie" misc@dartlang.org post originally written by Bob Nystrom. It is being posted here as the explanations still ring true.)

Bob writes:


"static", "final", and "const" mean entirely distinct things in Dart:

"static" means a member is available on the class itself instead of on instances of the class. That's all it means, and it isn't used for anything else. static modifies *members*.

"final" means single-assignment: a final variable or field *must* have an initializer. Once assigned a value, a final variable's value cannot be changed. final modifies *variables*.

"const" has a meaning that's a bit more complex and subtle in Dart. const modifies *values*. You can use it when creating collections, like const [1, 2, 3], and when constructing objects (instead of new) like const Point(2, 3). Here, const means that the object's entire deep state can be determ…