What’s new in Google Dart - Seth Ladd

837 views
762 views

Published on

The modern web is feature-rich and fast, and Dart gives you a familiar and productive toolchain to scale up your code and apps. Come learn what's new with the Dart project, and how you can use the class-based language, rich built-in libraries, productive editor, package manager, and more. You want more? How about Web Components and a Future-based DOM! You'll see lots of demos, with special attention to the Dart-to-JavaScript compiler.

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
837
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

What’s new in Google Dart - Seth Ladd

  1. 1. JAX 2013Seth Ladd, Developer Advocate, Dart#dartlangYour first-class upgrade to web development
  2. 2. #dartlang● Language and libraries● Tools● VM● Compiler to JavaScript
  3. 3. #dartlangrequire.jsBackboneBackbone MarionettejQueryModernizrmoment.jsdest templatesPhantomJSJasmineDocsDocsDocsDocsDocsDocsDocsDocsDocs"I just want towrite webapps!""Hi, I want tobuild a webapp"
  4. 4. #dartlangUnit testDart SDKWeb UIIntlPackages"Things areconsistent andclear."
  5. 5. #dartlangInside Google● Dozens to Hundreds ofEngineers● Millions of Lines of CodeBig and Complex● GWT● Closure● SoyLots of Layers● No edit/refresh● 24 min to see a change!!Low ProductivitySurely we can do better!
  6. 6. #dartlangImprove all the things!Structure Syntax Semantics Tools Core Libs RequiresCompilation forDevelopmentPerformanceVanilla JS ---- ---- ---- ---- ----No----Dart NoClosure ----Yes----CoffeeScript ---- ---- ----Yes----TypeScript ---- ----Yes----GWTYes----
  7. 7. #dartlangLightning Tour● Syntax● Semantics● Structure
  8. 8. #dartlangSimple syntax, ceremony freeclass Hug { Familiar
  9. 9. #dartlangSimple syntax, ceremony freeclass Hug {final num strength;Hug(this.strength); Terse
  10. 10. #dartlangSimple syntax, ceremony freeclass Hug {final num strength;Hug(this.strength);Hug.bear() : strength = 100;Named constructor
  11. 11. #dartlangSimple syntax, ceremony freeclass Hug {final num strength;Hug(this.strength);Hug.bear() : strength = 100;Hug operator +(Hug other) {return new Hug(strength + other.strength);}Operator overriding
  12. 12. #dartlangSimple syntax, ceremony freeclass Hug {final num strength;Hug(this.strength);Hug.bear() : strength = 100;Hug operator +(Hug other) {return new Hug(strength + other.strength);}void patBack({int hands: 1}) {// ...}Named, optional params w/ default value
  13. 13. #dartlangSimple syntax, ceremony freeclass Hug {final num strength;Hug(this.strength);Hug.bear() : strength = 100;Hug operator +(Hug other) {return new Hug(strength + other.strength);}void patBack({int hands: 1}) {// ...}String toString() => "Embraceometer reads $strength";}One-line function
  14. 14. #dartlangSimple syntax, ceremony freeclass Hug {final num strength;Hug(this.strength);Hug.bear() : strength = 100;Hug operator +(Hug other) {return new Hug(strength + other.strength);}void patBack({int hands: 1}) {// ...}String toString() => "Embraceometer reads $strength";}String Interpolation
  15. 15. #dartlangClean semantics and behavior
  16. 16. #dartlangClean semantics and behaviorExamples:● Only true is truthy● There is no undefined, only null● No type coercion with ==, +
  17. 17. #dartlangMissing getter?"hello".missing // ??Class String has no instance getter missing.NoSuchMethodError : method not found: missingReceiver: "hello"Arguments: []LogicalMore on this soon.
  18. 18. #dartlangIndex out of range?[][99] // ??RangeError: 99Logical
  19. 19. #dartlangVariable scope?var foo = top-level;void bar() {if (!true) { var foo = inside; }print(foo);}main() { bar(); } // ?? What will this print?top-level LogicalNohoisting
  20. 20. #dartlangScope of `this`?class AwesomeButton {AwesomeButton(button) {button.onClick.listen((Event e) => this.atomicDinosaurRock());}atomicDinosaurRock() {/* ... */}}Lexicalthis
  21. 21. #dartlangScalable structureFunctions ClassesLibrariesPackagesMixins Interfaceslibrary games;import dart:math;import players.dart;class Darts {// ...}class Bowling {// ...}Player findOpponent(int skillLevel) {// ...}
  22. 22. #dartlangLanguageWhatsNew!
  23. 23. #dartlangvar button = new ButtonElement();button.id = fancy;button.text = Click Point;button.classes.add(important);button.onClick.listen((e) => addTopHat());parentElement.children.add(button);Yikes! Button is repeated 6 times!Too many buttons
  24. 24. #dartlangMethod cascadesvar button = new ButtonElement()..id = fancy..text = Click Point..classes.add(important)..onClick.listen((e) => addTopHat());parentElement.children.add(button);
  25. 25. #dartlangInline initializationparentElement.children.add(new ButtonElement()..id = fancy..text = Click Point..classes.add(important)..onClick.listen((e) => addTopHat()));
  26. 26. One of these things is not like the otherObjectPersistableHugHug is notis-a PersistableDont polluteyourinheritancetree!
  27. 27. Dont inherit, mixin!ObjectPersistableHug Mixin
  28. 28. #dartlangMixinsabstract class Persistable {save() { ... }load() { ... }toJson();}class Hug extends Object with Persistable {Map toJson() => {strength:10};}main() {var embrace = new Hug();embrace.save();}Extend object &no constructors?You can be amixin!Apply the mixin.Use methodsfrom mixin.
  29. 29. #dartlangMetadata
  30. 30. #dartlangLazy-load librariesconst lazy = const DeferredLibrary(my_lib);@lazyimport my_lib.dart;void main() {lazy.load().then((_) {print(library loaded);// use functions from my_lib});}Mark the importas lazy.Declare the library isdeferred.Use a Future towait for library toload.Dart appJS filedart2jsJS fileDart libIn progress
  31. 31. #dartlangLibrariesWhatsNew!
  32. 32. JS-Interop#dartlangYES!
  33. 33. #dartlangProxies: the abstractionvar chart; // proxy chart objectcallback() {...} callback proxy
  34. 34. #dartlangJS-Interop examplevar api = js.context.chartsApi;var data = js.array([1,3,3,7]);var chart = new js.Proxy(api.BubbleChart, query(#chart));chart.draw(data);var api = chartsApi;var data = [1,3,3,7];var chart = new api.BubbleChart(querySelector(#chart));chart.draw(data);
  35. 35. #dartlangMirror-based reflection● Source code and run-time● Reflect on classes andinstances● Introspect and invoke
  36. 36. #dartlangUsing mirrors to build a logging proxyClient Proxy Delegatex.hello()d.hello()print()log()
  37. 37. #dartlangReflection and metaprogrammingimport dart:mirrors;class LoggingProxy {InstanceMirror mirror;LoggingProxy(delegate): mirror = reflect(delegate);noSuchMethod(Invocation invocation) {var name = invocation.memberName;print(${name} was called);return mirror.delegate(invocation);}}Import the mirrorslibrary.
  38. 38. #dartlangReflection and metaprogrammingimport dart:mirrors;class LoggingProxy {InstanceMirror mirror;LoggingProxy(delegate): mirror = reflect(delegate);noSuchMethod(Invocation invocation) {var name = invocation.memberName;print(${name} was called);return mirror.delegate(invocation);}}Get a mirror of anobject.
  39. 39. #dartlangReflection and metaprogrammingCapture all calls tothis proxy.import dart:mirrors;class LoggingProxy {InstanceMirror mirror;LoggingProxy(delegate): mirror = reflect(delegate);noSuchMethod(Invocation invocation) {var name = invocation.memberName;print(${name} was called);return mirror.delegate(invocation);}}
  40. 40. #dartlangReflection and metaprogrammingLog the call.import dart:mirrors;class LoggingProxy {InstanceMirror mirror;LoggingProxy(delegate): mirror = reflect(delegate);noSuchMethod(Invocation invocation) {var name = invocation.memberName;print(${name} was called);return mirror.delegate(invocation);}}
  41. 41. #dartlangReflection and metaprogrammingDelegate the callthrough themirror.import dart:mirrors;class LoggingProxy {InstanceMirror mirror;LoggingProxy(delegate): mirror = reflect(delegate);noSuchMethod(Invocation invocation) {var name = invocation.memberName;print(${name} was called);return mirror.delegate(invocation);}}
  42. 42. #dartlangReflection and metaprogrammingclass Greeter {hello() => print("hello!");}void main() {var greeter = new LoggingProxy(new Greeter());greeter.hello();}// Symbol("hello") was called// hello!From LoggingProxyFrom Greeter
  43. 43. #dartlangThe web is an async world,but too many callbacks leads toAsync with callbacks
  44. 44. #dartlangAsync with futures
  45. 45. #dartlangdoStuff((results) {handle(results);}, onError: (e) {handleError(e);});Future future = doStuff();future.then(handle);future.catchError(handleError);doStuff().then(handle).catchError(handleError);Traditional callbacks Futures
  46. 46. #dartlangcatService.getCatData("cute", (cat) {catService.getCatPic(cat.imageId, (pic) {imageWorker.rotate(pic, 30, (rotated) {draw(rotated);});});});4 levelsdeep!Scary
  47. 47. #dartlangcatService.getCatData("cute", (cat) {catService.getCatPic(cat.imageId, (pic) {imageWorker.rotate(pic, 30, (rotated) {draw(rotated, onError:(e) { draw(ohNoeImage); });}, onError: (e) { draw(ohNoeImage); });}, onError: (e) { draw(ohNoeImage); });}, onError: (e) { draw(ohNoeImage); });Duplicateerrorhandling!More scary
  48. 48. #dartlangcatService.getCat("cute").then((cat) => catService.getCatPic(cat.imageId)).then((pic) => imageWorker.rotate(pic, 30)).then((rotated) => draw(rotated)).catchError((e) => print("Oh noes!"));The Future looks bright
  49. 49. Future cute = catService.getPic("cute");Future nyan = catService.getPic("nyan");Future.wait([cute, nyan]).then((pics) => imageWorker.blend(pics[0], pics[1])).then((cuteNyan) => draw(cuteNyan)).catchError((e) => print("Oh noes!"));#dartlangRequest twopics.Wait for bothto arrive.Work withboth pics.Composing futures
  50. 50. Streams are the repeating analog to Futures.Nearly all repeating events in Dart are Streams.#dartlangStreamsNew!
  51. 51. query(textarea).onKeyPress.where((e) => e.keyCode >= 32 && e.keyCode <= 122).map((e) => new String.fromCharCode(e.charCode)).first.then((char) => print(First char=$char));#dartlangElement abstract class...final Stream<KeyboardEvent> onKeyPressapi.dartlang.org
  52. 52. #dartlangHTMLWhatsNew!
  53. 53. window.navigator.getUserMedia(audio:true, video: true).then((mediaStream) {var video = new VideoElement()..autoplay = true..src = Url.createObjectUrl(mediaStream)..onLoadedMetadata.listen((e) => /* ... */);document.body.append(video);}).catchError(reportIssue);#dartlangWeb programming with Dart
  54. 54. String name = (query(#cat-name) as InputElement).value;HttpRequest.request(/cats,method: POST,sendData: stringify({name:name}),requestHeaders: {Content-Type: application/json}).then((req) {catNames.add(name);}).catchError((e) => print(e));#dartlangXHR with Dart
  55. 55. @observableclass Person {String name = ;}@observableList people = toObservable([]);addPerson() => people.add(new Person());#dartlangData Binding<button on-click="addPerson()">Add</button><ul><template repeat="p in people"><li>{{p.name}} - <input type="text" bind-value="p.name"></li></template></ul>
  56. 56. #dartlangEncapsulationCustom ElementStructure Behavior Styles
  57. 57. <link rel="import" href="clickcounter.html">...<div is="click-counter" id="click_counter" count="{{startingCount}}"></div>#dartlangCustom ElementsImport the custom element code.Use the custom element.
  58. 58. #dartlangCustom Elements<element name="click-counter" constructor="CounterComponent" extends="div"><template><button on-click="increment()">Click me</button><br /><span>(click count: {{count}})</span></template><script type="application/dart" src="xclickcounter.dart"></script></element>class CounterComponent extends WebComponent {int count = 0;void increment() {count++;}}
  59. 59. #dartlangTools &EcosystemWhatsNew!
  60. 60. #dartlangFast development cyclesDartium: Chromium + Dart VMInception Developmentdart2jsDeliveryTest OtherBrowsersNo compiles required! Compile to JS
  61. 61. #dartlang
  62. 62. #dartlangtry.dartlang.org
  63. 63. #dartlangtest(add, () {var answer = add(1, 2);expect(answer, equals(3));});Continuous integration, native Dart supportHeadless Chrome, command-line testing
  64. 64. #dartlang● Download● Manage● Publish● BrowsePub, a package manager for DartAvailable in pub.dartlang.org:● MVC frameworks● Template systems● Google APIs● Encryption● Server-side frameworks● DB drivers● Parsers● Game libraries● Much, much more!
  65. 65. #dartlangExport Flash movies/gamesto Dart from Flash Pro
  66. 66. #dartlangSize & SpeedWhatsNew!
  67. 67. #dartlangMore complex apps#perfmatters
  68. 68. #dartlangBetter performance == Better battery#perfmatters
  69. 69. #dartlangdart2jsGenerating smaller JavaScriptLibrariesapp.dartLibrariesapp.jsPackagesPackagesTree shakingMinificationTypeinferencingSourceMap
  70. 70. #dartlangGenerated JS with dart:htmlimport dart:html;class Person {String firstName;String lastName;Person(this.firstName, this.lastName);}main() {var bob = new Person(Bob, Smith);var msg = query(#msg);msg.text = bob.firstName;}$$.Person = {"": "Object;firstName,lastName"};$.Person$ = function(firstName, lastName) {return new $.Person(firstName, lastName);};$.main = function() {var bob = $.Person$("Bob", "Smith");document.querySelector("#msg").textContent = bob.firstName;};
  71. 71. #dartlangGenerated JS, minified!$$.mM={"":"a;Sz,dq"}$.PH=function(a,b){return new $.mM(a,b)}$.E2=function(){var z=$.PH("Bob","Smith")document.querySelector("#msg").textContent=z.Sz}$$.Person = {"": "Object;firstName,lastName"};$.Person$ = function(firstName, lastName) {return new $.Person(firstName, lastName);};$.main = function() {var bob = $.Person$("Bob", "Smith");document.querySelector("#msg").textContent = bob.firstName;};Minified
  72. 72. #dartlangmain() Libraryfunc1 func2 funcX funcYimportscallsTree-shakingcompiler (dart2js)main() func2 funcX
  73. 73. #dartlangDart VM
  74. 74. #dartlangMore structure, less baggage● Explicit and static structure● Real arrays● Real classes● Direct calls, no prototype chains to check● Globally track field types
  75. 75. #dartlangUnlock more of your CPUSIMDSIMD
  76. 76. #dartlangHigher is better, as of 2013/05/12dartlang.org/performance2X
  77. 77. #dartlangHigher is better, as of 2013/05/12x86, Chrome for Android1.48X2.42X
  78. 78. ● Server-side● Testing● Isolates for concurrency● Lots more...Theres more new stuff!
  79. 79. #dartlangTry Dart!● Download from dartlang.org● Join +Dartisans● Send pull requests at Github● Ask on Stack Overflow#dartlang
  80. 80. #dartlang● Stable language● Stable core libs● Compiles to JavaScript● Evolved platform● CommitmentReady foryour app!
  81. 81. Thank You!Find us at dartlang.org#dartlang

×