Dart
a modern web language
or why web programmers need more structure

Kasper Lund & Lars Bak
Software engineers, Google Inc.

Object-oriented language
experience: 26 + 12 years

 
The Web Is Fantastic

● The web is everywhere
● Developing small applications is easy
● No required installation of applications
● Support for incremental development
● Friendly competition drives the industry

 
The Web Platform Wheel of Improvements

New browser features

I

n

n

o

v

a

t
i

o

n

i

n

A

p

p

s

Perform ance

 
 
 
JavaScript Performance Improvements

V8 Benchmark Suite v3 - higher numbers are better

Challenges for the Web 

● Programmer productivity
● Application scalability
● Raw execution speed
● Startup performance

..... if we don't innovate, the web will lose to mobile apps

 
Welcome to the Dart Platform

A web programming platform that has accepted these challenges

High level goals
● Simple productive programming language
● Support for programming in the large
● Predictable high performance
● Ultra-fast startup
● Compatibility with modern browsers

 
Fundamental JavaScript Issues

JavaScript is everywhere, but it isn't necessarily the right tool for every job

JavaScript Issue #1: Where Is The Program? 

JavaScript code is hard to reason about
● Almost no declarative syntax
● Borderline impossible to find dependencies
● Monkey patching makes it even worse

Understanding the program structure is crucial
● Easier code maintenance and refactoring
● Better debuggability and navigation of code

Where Is The Program? 
All declarations are actually statements that must be executed

function Point(x, y) {
  this.x = x;
  this.y = y;
}

Fields are "declared" implicitly by the 
statements in the constructor.

JavaScript

 
Where Is The Program?
It can be pretty hard to analyze what actually gets declared

function Point(x, y) {
  if (Object.defineProperty) {
    Object.defineProperty(this, 'x', { value: x, writable: false });
    Object.defineProperty(this, 'y', { value: y, writable: false });
  } else {
    this.x = x;
    this.y = y;
  }
}

Control flow makes it difficult to statically 
tell which fields you end up with

JavaScript

 
JavaScript Issue #2: Keep On Truckin' 

JavaScript has a keep on truckin' mentality
● Mistakes are tolerated
● Wrong types lead to unusable results
● Almost anything goes...

 Throwing errors eagerly is better
● Easier to locate the source of errors
● Forces more errors during testing
● Gives confidence in deployed apps

Keep On Truckin': Constructors Are Just Functions
Seems nice and simple, but leads to lots of issues

function Point(x, y) { 
  this.x = x;
  this.y = y;
}

JavaScript

var point = Point(2, 3);     // Whoops, forgot to write new but
assert(point == undefined);  // that's okay because we get undefined back
assert(x == 2 && y == 3);    // and now we have more global variables!

 
Keep On Truckin': Accessing Non-existing Properties 
Typos lead to code that runs but does that wrong thing

var request = new XMLHttpRequest();
...
request.onreadystatechange = function() {
  if (request.readystate == 4) {
    console.log('Request done: ' + request.responseText);
  }
};

JavaScript

 
Keep On Truckin': Accessing Non-existing Properties 
Typos lead to code that runs but does that wrong thing

var request = new XMLHttpRequest();
...
request.onreadystatechange = function() {
  if (request.readystate == 4) {
    console.log('Request done: ' + request.responseText);
  }
};

Did you mean: 
readyState?

JavaScript

 
Keep On Truckin': Implicit Conversions 
Mixing objects and immutable values  

var string = 'the quick brown fox';   // strings are values, not objects
string.hash = md5(string);            // string -> object
assert(string.hash == undefined);     // string -> object (a different one)

JavaScript

 
Keep On Truckin': Implicit Conversions 
This just gets worse and worse

true but why?

true but why?

true but why?

JavaScript

               assert(2.0 == '2' == new Boolean(true) == '1');

Enough implicit conversions to 
make your head explode?

 
JavaScript Issue #3: Unpredictable Performance

Advice: Use the efficient subset of JavaScript
● VMs have been optimized for certain patterns
● Benefit from the performance improvements

Harder than it sounds
● Lots of differences between browsers
● Not just about syntactic constructs

JavaScript

Efficient 
JavaScript

JavaScript performance is very unpredictable
Building high-performance web apps in JavaScript is tricky

Summary of JavaScript Issues

● Program structure is hard to find, understand, and reason about
● Monkey patching core objects does not make it any easier 
● Keep on truckin' mentality hides bugs and limits productivity
● Performance is unpredictable and really bad for application startup

We believe innovation is needed to improve productivity of web developers

 
The Dart Programming Language

In a nutshell

Dart in a Nutshell

● Unsurprising simple object-oriented programming language 
● Class-based single inheritance with interfaces 
● Familiar syntax with proper lexical scoping
● Single-threaded with isolate-based concurrency
● Optional static types

Syntax
JavaScript

Objects
Smalltalk

Isolates
Erlang

Dart =

Types
Strongtalk

Concepts
C#

 
First Dart Example
Point example that computes distance to origin

class Point {
  var x, y;
  Point(this.x, this.y);
  operator +(other) => new Point(x + other.x, y + other.y);
  toString() => "($x,$y)";
}

Dart

main() {
  var p = new Point(2, 3);
  print(p + new Point(4, 5));
}

 
Optional Static Types

Static type annotations convey the intent of the programmer
● They act as checkable documentation for code and interfaces 
● They can be generic which makes them very useful for collections
● They have no effect on runtime semantics

The Dart type system is considered unsound since downcasts are allowed
However, these downcasts can be validated at runtime

 
First Dart Example
Now with static types

class Point {
  num x, y;
  Point(this.x, this.y);
  Point operator +(Point other) => new Point(x + other.x, y + other.y);
  String toString() => "($x,$y)";
}

Dart

main() {
  Point p = new Point(2, 3);
  print(p + new Point(4, 5));
}

 
Dart Has Covariant Generic Types
An apple is a fruit, so a list of apples is clearly a list of fruits?

main() {
  List<Apple> apples = tree.pickApples();
  printFruits(apples);
}

void printFruits(List<Fruit> fruits) {
  for (Fruit each in fruits) print(each);
}

Dart

 
Demo: Runtime Type Checking In Dart

It's demo time...

 
Potpourri of Cool Dart Language Features

 
Named Constructors
No overloading based on argument types

class Point {
  var x, y;
  Point(this.x, this.y);
  Point.polar(r, t) : x = r * cos(t), y = r * sin(t);
}

main() {
  var p = new Point(2, 3);
  var q = new Point.polar(3, 0.21);
}

Dart

 
Interfaces With Default Implementations
Instances can be constructed from interfaces

interface List<E> implements Collection<E> default ListFactory<E> {
  List([int length]);
  ...
}

main() {
  var untyped = new List();         // any object can be added
  var typed = new List<Point>(12);  // only points can be added
}

Dart

 
Cascaded Calls
Multiple calls to the same object

void drawCircle(CanvasElement canvas, int x, int y, int size) {
  canvas.context..beginPath()

                ..arc(x, y, size, 0, Math.PI * 2, false)
                ..fill()
                ..closePath()
                ..stroke();
}

Dart

 
Proper Capturing of Loop Variables
Prints 01234567 rather than 88888888 as in JavaScript

main() {
  var closures = [];
  for (var i = 0; i < 8; i++) closures.add(() => i);  // collect
  for (var c in closures) print(c());                 // evaluate
}

Dart

For each iteration of the loop, a fresh 
copy of the variable i is captured.

 
Dart Is Beautiful 

Dart programs are declared and easy to read in the source code

Clean semantics without surprises
● No strange implicit conversions are performed
● Libraries cannot be monkey patched at runtime

Java, C#, and JavaScript programmers: 

You can be productive in Dart within a few hours

 
The Dart Project

Greater than the sum of its parts

The Language Is Only a Part of the Story

Making Dart great for web development depends on entire platform

Developers also need:
● Fast execution and startup
● Tools for development and code analysis 
● Great integration with the DOM

 
Deployment and Execution

Application 
source code

+

Libraries

Dart tools

dart2js

Dart virtual 
machine

in Dartium or standalone

JavaScript

Dart snapshot

runs in all modern browsers

very fast startup

 
Dart Is Compatible With Modern Web Browsers

http://buildbot.dartlang.org/

 
Translation To JavaScript

There is a compiler that translates Dart to JavaScript (dart2js)
The entire compiler is implemented in Dart

Dart

 class Point {
   var x, y;
   Point(this.x, this.y);
   toString() => "($x,$y)";
 }

JavaScript

 Point = {
   super: "Object",
   fields: ["x", "y"],
   toString$0: function() {
     return '(' + str(this.x) + 
            ',' + str(this.y) + 
            ')';
   }
 };

   
 
Dart Tree Shaking

Tree shaking is a pre-deployment step that eliminates unused code
● Unused classes and methods are eliminated
● Applications are only penalized for what they use
● Easy process since Dart apps are declared

Tree shaking is used by dart2js
● Reduces the download size
●

Improves startup times

 
Dart Snapshots

Binary form of an entire Dart app
● Speeds up loading by 10x

Created by loading the app and serializing the heap
● Snapshots contain classes and methods
● Only works with the Dart VM

Benefits
● No need to scan and parse source code
● Crucial on slower mobile devices

 
The Future

Please put your sunglasses on

The Future of the Language

The Dart language is frozen for the first version
Except these few remaining issues:
● Eliminate interfaces and rely on abstract classes
●
● Add support for annotations

Introduce mixins for better sharing

 
The Dart Timeline

....

2009

2010

2011

2012

2013

cript

S
a
v
a
J

ot
p
S

art
D

st
d fa
st a

n

s!
s
e
c
c
u
S

u
b
o
R

 
Dart Developer Release in Fall 2012

We are serious about making Dart the next generation web app platform!

The fall release will include:
● Language specification
● Libraries for web and server development
● Programming environment
● Virtual machine + browser integration
● Translator to JavaScript

 
Dart Is Open Source

Dart is available under a BSD license
Developed in the open (code reviews, build bots, etc.)
Excited and active community

Online resources
● Primary site - http://www.dartlang.org/
● Code - http://dart.googlecode.com/
● Libraries - http://api.dartlang.org/
● Specification - http://www.dartlang.org/docs/spec/

Please try out Dart

 
More Dart @ Google I/O

Wednesday
● 2:45 - 3:45pm: Putting the App Back into Web App (room 3)
● 4:00 - 5:00pm: Migrating Code from GWT to Dart (room 3)
● 2:45 - 6:45pm: Dart Office Hours (Chrome Demo Floor)

Thursday
● 4:00 - 6:00pm: Bullseye - Your First Dart App (code lab)

 
Dart Summary

Dart is an unsurprising object-oriented language, instantly familiar to most
Dart allows you to write code that tools and programmers can reason about
Dart applications work in all modern browsers by translating to JavaScript

      Making fast virtual machines is easy ... try making a new language

 
Thank You!

That is it folks...

kasperl@google.com & bak@google.com

