for Java Developers About Me C# since 2005 till 2012 Java since - - PowerPoint PPT Presentation
for Java Developers About Me C# since 2005 till 2012 Java since - - PowerPoint PPT Presentation
for Java Developers About Me C# since 2005 till 2012 Java since 2012 JavaScript, Dart since 2013 Working at Farata Systems Conduct trainings 2 What is Dart? New programming language and platform created by
About Me
- C# since 2005 till 2012
- Java since 2012
- JavaScript, Dart since 2013
- Working at Farata Systems
- Conduct trainings
2
What is Dart?
3
New programming language and platform
created by for Web development
3
4
Blink… WebKit… Reader…
Code Search… Chrome Frame…
Dart is Truly OSS
- Public commits
- Public issue tracker
- Public code reviews
- Accept contributions
5
- Dart is ECMA standard (TC52)
- Also ECMA: JavaScript, C#, C++/CLI, JSON, ActionScript
6
What does it mean? ECMA committee standardizes syntax, semantics, core libraries Why it is important? Safe to develop
- wn VMs and embed
in browsers
Team
- Lars Bak - HotSpot, V8, a Smalltalk VM, BETA
- Kasper Lund - HotSpot, V8, OOVM
- Gilad Bracha - Java Specification, Strongtalk, Newspeak
- Many other engineers
7
http://youtu.be/huawCRlo9H4
8
Timeline
9
Sep 1, 2011 Oct 10, 2011 Apr 9, 2014
1.0 Release First commit Announcement
Nov 14, 2013
1.3 Release
Dart at a glance
- Runs in VM
- Compiles to JavaScript
- Dynamically typed
- Object-oriented
- Single inheritance
- Single-threaded
- Familiar sytax
10
How is it better than JS?
- Faster
- Predictable (no hoisting, no type coercion, etc.)
- Rich standard libraries
- Structured apps
- Good tooling
- Packaging system
11
What's Your Benefit?
12
Q: Front-end Developer? A: Build reliable apps faster Q: Back-end Developer? A: Probably just curiosity
Language Tour
13
Hello World
14
// Formal example void main(List<String> args) { print('Hello from Dart!'); } // Shorter version main() => print('Hello from Dart!');
- Explicit entry point
Built-in Types
15
int
var i = 1; var hex = 0xABCD;
double
var d = 1.2; var exp = 1.2e9;
String
var s1 = 'single quotes'; var s2 = "double quotes";
bool
var b1 = false; var b2 = true;
Symbol
var sym1 = #mySymbol; var sym2 = const Symbol('mySymbol');
List
var list = ['item1', 'item2', 'item3'];
Map
var map = {'key1': 'val1', 2: 'val2', []: 'val3'};
JSON is valid Dart Syntax
16
var map = { 'firstName' : 'John', 'lastName' : 'Doe', 'age' : 30, 'addresses' : [ { 'street': '' //... }, { 'street': '' //... } ] };
- List and Map literals make JSON a valid Dart syntax
Optional Types Example
- Best practice - explicit types for method signatures and
class members, for local variables - var
main() { var a = 1; var b = 2; var c = divide(a, b); assert(c == 0.5); }
- divide(a, b) {
return a / b; } void main() { int a = 1; int b = 2; double c = divide(a, b); assert(c == 0.5); }
- double divide(int a, int b) {
return a / b; }
17
Optional Types Rules
- All type annotations can be omitted
- Has no effect at runtime
- App without types has the same semantics
- Do not cause errors, only warnings
- You can always “compile” and run your program
18
Benefits of Type Annotations
- Act as documentation
- Advanced tools support (completion, code navigation, etc.)
- Error detection via type checker
- Can improve performance while compiling to JavaScript
19
Declaring Variables
20
- null is default value for all types
- Supports final and const
var str1 = ''; // type is dynamic (implicit) String str2 = ''; // type is String Object str3 = ''; // type is Object dynamic str4 = ''; // type is dynamic (explicit)
Functions
21
// Top-level functions void log(String message) { print(message); } // Single expression functions void log(String message) => print(message); // Nested functions void main() { void log(String msg) => print(msg); log('done'); }
Higher-order functions
22
// Accept function as parameter void doSomething(Function callback) { //... callback(); } doSomething(() => log('done')); // Return function Function getLogger() { return (String msg) => log(msg, level: 'INFO'); } // Assign to a variable var logger = getLogger(); logger('done'); // Define function-type aliases typedef void Logger(String msg); Logger getLogger() { return (String msg) => log(msg, level: 'INFO'); }
Optional Parameters
23
/// [level] parameter has default value void log(String msg, [Error error, String level = 'INFO']) { //... } log('Bad value'); log('Bad value', new ArgumentError()); log('Bad value', new ArgumentError(), ‘ERROR');
Positional parameters:
void log(String msg, {Error error, String level}) { //... } log('Bad value'); log('Bad value', level: 'ERROR'); log('Bad value', level: 'ERROR', error: new ArgumentError());
Named parameters:
Classes
24
Class members
25
class WampService { // Instance member WebSocket socket; // Final member final String id; // Static member static int buffer_size = 0; // Const member static const String URL = ‘ws://localhost/ws’; }
- Declaratively defined classes and members
Getters & Setters
26
class WampService { WebSocket _socket; get socket => _socket != null ? _socket : _socket = new WebSocket(); set socket(WebSocket s) { if (_socket.readyState != WebSocket.OPEN) _socket = s; else throw new StateError(); } }
Constructors
27
class Person { String name; DateTime birthday; Person(String name, DateTime birthday) { this.name = name; this.birthday = birthday; } }
Automatic Assignment
28
class Person { String name; DateTime birthday; Person(this.name, this.birthday); }
Initializers
29
class Person { String name; DateTime birthday; Person(): name = '', birthday = new DateTime.now(); }
Named constructors
30
class Collection { //... // Ordinary constructor Collection(List source) {} // Named constructor Collection.empty() {} } var c = new Collection.empty();
Factory constructors
31
// Publicly expose abstract class abstract class Service { void doSomething(); // Expose concrete implementation via factory constructor factory Service() => new _DefaultService(); } // Internally provide concrete implementation class _DefaultService implements Service { void doSomething() {} } // You can invoke factory constructors of abstract classes var s = new Service();
- Indirect instantiation
Factory constructors
32
class Service { static final Map<String, Service> _cache = {}; String name; factory Service(String name) => _cache.putIfAbsent(name, () => new Service._(name)); Service._(this.name); }
- Caching pattern
Java: Builder pattern
33
public class User { private String firstName; // required private String lastName; // required private String phone; // optional private int age; // optional private User(UserBuilder builder) { this.firstName = builder.firstName; this.lastName = builder.lastName; this.age = builder.age; this.phone = builder.phone; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getAge() { return age; } public String getPhone() { return phone; } // TO BE CONTINUED... // Static nested class public static class UserBuilder { private String firstName; private String lastName; private String phone; private int age;
- public UserBuilder firstName(String firstName) {
this.firstName = firstName; return this; } public UserBuilder lastName(String lastName) { this.lastName = lastName; return this; } public UserBuilder age(int age) { this.age = age; return this; } public UserBuilder phone(String phone) { this.phone = phone; return this; } public User build() { return new User(this); } } }
Dart: a kind of “Builder pattern”
34
class User { String firstName; String lastName; String phone; int age; // Here "this" enables type checking. User({this.firstName, this.lastName, this.phone, this.age}); } // Usage var user = new User( firstName: 'John', lastName: 'Doe', phone: '+123456789', age: 30);
Cascade operator
35
// Equivalent declaration class User { String firstName; String lastName; String phone; int age; User(this.firstName, this.lastName); } // Usage var user = new User('John', 'Doe') ..age = 30 ..phone = '+123456789';
Automatic Fluent APIs
36
querySelector('h1') ..text = 'Welcome!' ..classes.add('caption') ..onClick.listen((_) => print('clicked'));
Abstract Classes
37
abstract class AuthService { void login(String user, String password) { /*...*/ } void register(String user, String email, String password); } class BasicAuthService extends AuthService { void register(String user, String email, String password) { /*...*/ } }
- abstract keyword only for class declaration
Inheritance
38 abstract class AuthService { AuthService(String token) { /*...*/ } void login(String user, String password) { /*...*/ } void register(String user, String email, String password); } class BasicAuthService extends AuthService { BasicAuthService(String token): super(token); @override void login(String user, String password) { _ensureUnique(user); super.login(user, password); } @override void register(String user, String email, String password) { /*...*/ } _ensureUnique(String user) { /*...*/ } }
Interfaces
- Each class implicitly defines an interface
39
abstract class AuthService { String get token => ''; final String URL = ''; AuthService(String token) { /*...*/ } void login(String user, String password) { /*...*/ } void register(String user, String email, String password); } class BasicAuthService implements AuthService { String get token => ''; final String URL = ''; @override void login(String user, String password) { /*...*/ } @override void register(String user, String email, String password) { /*...*/ } }
Mixins
40
abstract class Storage { void save() { /*...*/ } String toJson(); } class Person extends Object with Storage { String name; String toJson() => '{ "name": "$name" }'; } var p = new Person(); p.save();
- Mixin class must: extend Object, declare no constructors,
no calls to super
Generics
41
var dynamics = new List(); // new List<dynamic>(); dynamics.add('string'); // always OK dynamics.add(42); // always OK String s = dynamics.first; // always OK String i = dynamics.last; // FAILS in checked mode
- You are not required to use them
- dynamic is default
Covariance
42
class A {} class B extends A {}
- List<A> listA = new List<B>();
listA.add(new A()); // FAILS in checked mode listA.add(new B()); // always OK A b1 = listA.last; // always OK B b2 = listA.last; // always OK
- No wildcards or explicit bound constraints required
Contravariance
43
class A {} class B extends A {} void acceptsListOfB(List<B> list) => list.add(new B()); void acceptsList(List list) => list.add(new B()); // No way to hint we use it only contravariantly. acceptsListOfB(new List<A>()); // OK static checking // FAILS in checked mode // OK in runtime // Workaround - loose the declaration acceptsList(new List<A>()); // OK static checking // OK in checked mode // OK in runtime // However, silences type checking and permits invalid usage acceptsList(new List<int>()); // OK static checking // OK in checked mode // FAILS in runtime
Libraries
- Dart libraries is a more flexible equivalent to Java packages
44
// myapp.dart library myapp; import 'dart:io'; part 'services.dart'; part 'models.dart';
// services.dart part of myapp;
// models.dart part of myapp; // services.dart library myapp.services;
// models.dart library myapp.models;
// myapp.dart library myapp; import 'services.dart'; import 'models.dart'; export 'services.dart' show IntegrationService;
Futures
45
new Future(() => print('Async job 1')) .then((_) => print('Async job 2')) .then((_) => print('Async job 3')) .catchError((err) => print(err));
Streams
46
Stream<List<int>> inputStream = new file.openRead(); inputStream .transform(UTF8.decoder) .transform(new LineSplitter()) .listen((String line) => print(line));
VM
- No bytecode
- Dart is a native language for Dart VM
- Enables dev tools and server-side apps
- In future - embedded into browsers
47
Performance
- Dart VM in average 1.5-2 times faster than JS/V8
- dart2js is almost the same as JS/V8
- 10x faster startup using snapshots
48
Benchmarks
49
dart js: v8 dart2js: v8
- More here: https://www.dartlang.org/performance/
Tools
50
Dart Editor
51
IntelliJ IDEA/WebStorm
52
Dartium
53
Pub
54
More Tools
- dart2js
- dartanalyzer
- dartfmt
- docgen
55
Resources
- https://www.dartlang.org
- Articles
- Benchmarks
- AngularDart
- DartlangTV YouTube channel
56
Thanks!
Contacts:
- twitter.com/antonmoiseev
- a@antonmoiseev.com
57