SlideShare a Scribd company logo
1 of 57
Download to read offline
© 2015 Farata Systems
Dart for Java
Developers
Yakov Fain, Farata Systems
Farata Systems and SuranceBay
surancebay.comfaratasystems.com
Our First Dart App: Easy Insure
http://easy.insure
Why Learn Google Dart
• Dart is a productive way to develop future JavaScript
apps today
• Comes with a complete set of dev tools
• Will help you to ease into the EcmaScript 6 developement
in 2016
Dart: Java Simplified
• Program with classes and/or with functions
• You can, but don’t have to declare variable types.
• Any class is an interface
• No data access qualifiers
• Single-threaded but supports concurrency
• No checked exceptions
• No autoboxing/unboxing
• IDEs: Dart Editor, IntelliJ IDEA, WebStorm, Eclipse Sublime Text…
• Write in Dart and run either in Dart VM or as JavaScript on any browser
Why Developing with Dart VM ?
• Developing in Dart is more productive than in JavaScript.
A static code analyser shows errors as you type.
• Instanteneous feedback from the VM - no bytecode is
generated for running in Dart VM.
• During development there’s no need to transpile code to
JS as in GWT.
• Your program can run standalone in Dart VM.
• Production deployment is done in JavaScript.
The Dart App Entry Point
A single entry point to any Dart app is a function main():

main() {

print('Hello world!');

}
The Dart App Entry Point
A single entry point to any Dart app is a function main():

main() {

print('Hello world!');

}
Or with command-line arguments:

import 'package:args/args.dart';



main(List<String> args) {



final parser = new ArgParser();

argResults = parser.parse(args);



List<String> someArgs = argResults.rest;



print(‘Got the argument ${someArgs[0]}');



}
Checked Mode
main() {

print('Adding numbers: ${add (2,3)}');

print('Adding strings: ${add ("Hello ","World")}');

}



add (num a, num b){



return a+b;

}
Importing Packages
• SDK comes with libraries whose names start with dart:



• You can add packages in the directory packages of your
project are app dependencies. Imports start with
package:
import 'dart:math';
import 'package:args/args.dart';
Dart Libraries
• dart:core
• dart:async
• dart:math
• dart:io
• dart:html
• dart:mirrors
• dart:convert
Package Dependencies
• Dart package manager is
called pub
• Dependencies are specified in
the file pubspec.yaml.
• Package versions are locked
in the file pubspec.lock.
name: stock_quote_console

version: 0.0.1

description: A stock quote app

environment:

sdk: '>=1.0.0 <2.0.0'

dependencies:

args: any

dev_dependencies:

unittest: any
pubspec.yaml
The central repo pub.dartlang.org has 1000+ packages
12
Selected pub commands
• pub get - retrieves packages (dependencies)
• pub upgrade - upgrades packages and regenerates
pubspec.lock
• pub serve - starts dev http server
• pub run - runs Dart scripts using dependencies from
pubspec.yaml
• pub build - generates and copies assets into the build dir
• pub global - run Dart packages installed anywhere on the
computer, pub.dartlang.org, or GitHub
Demo
Functions-only app 

Using pub to get dependencies 

Command-line arguments
IDEA module: StockQuoteConsole
Dart Classes
• Name class files in small letters with _ as a word separator
• Constructors support short syntax for variable initializations
• No keywords for public, protected, private.
• If a var name start with _ it’s private on a library level
• No method overloading
• Getters and setters are specified with get and set keywords
Class Stock
class Stock {

String _symbol;

double _price;



Stock (this._symbol);



double get price => _price==null?

_price=getFromYahoo():_price;



set price(double value){

_price = value;

}



String get symbol => _symbol;



set symbol(String value){
// some other processing may go here 

_symbol = value;

}

}
private vars
constructor
lazy getter
setter
Class Stock
class Stock {

String _symbol;

double _price;



Stock (this._symbol);



double get price => _price==null?

_price=getFromYahoo():_price;



set price(double value){

_price = value;

}



String get symbol => _symbol;



set symbol(String value){

_symbol = value;

}

}
private vars
constructor
lazy getter
setter
Stock stock = new Stock("IBM");


var price = stock.price;
Constructors
short form
named
optional param
class Customer {


int _id;

String name;



Customer(this._id, this.name);



Customer.taxExempt(int id, String name){

// Do something lowering taxes

}
Customer.optName(this._id, {this.name});





factory Customer.mafia(int id, String name){

if (name == "Don Carleone") 

return new Customer.taxExempt(id, name);

else 

return new Customer(id, name);

}

}
factory
Cascade Operator ..
• Avoid repeating the object name
• You can use method cascades .. on any object.
• Every .. refers to the original object, not to the
result of the previous method.
querySelector('#abutton') // Get an object 

..text = 'Confirm' // Use its members

..classes.add('important')

..onClick.listen((e) => window.alert('Confirmed!'));
Exceptions
• All exceptions are unchecked
• You can throw any objects: 



throw “Something happened”;
try {



// Do stuff here



} on NoSuchMethodError catch (e) {



print(‘Error: ${e.stackTrace}');

} on RangeError catch (e) {



print(‘Error: ${e.stackTrace}');

} on TypeError catch (e) {



print(‘Error: ${e.stackTrace}');

} catch (e) {



print('$e');

}
Code Structure
Package
Libraries
Classes Functions
Abstract

classes
Mixins
deploy and version
import
Libraries
library stock_quote;



import 'dart:math';

import 'dart:io';

import 'package:args/args.dart';



part "stock.dart";

part "stock_quote_generator.dart";



main(List<String> args) {
…
}
part of stock_quote;



class Stock {
…

}
part of stock_quote;



class StockQuoteGenerator {



…
}
Combine classes and top-level functions into libraries.
Demo
• Classes
• Getters
• Setters
• Libraries
IDEA module: StockQuoteClassesConsole
Mixins
• Mixin is a class with functionality that can be added to another class
using the with keyword
• You can add multiple mixins to the class declaration
class Bond extends Security with TradeReporter{


}
Java 8 interfaces are not mixins. They can’t have state.
class Bond extends Security 

with TradeReporter{


double faceValue;

DateTime maturityDate;



Bond(String name): super(name);



}
Mixin Sample
class Security{



String name;



Security(this.name);



}
class Stock extends Security{



String symbol;

double previousClosingPrice;



Stock(String name): super(name);



}
class Bond extends Security 

with TradeReporter{


double faceValue;

DateTime maturityDate;



Bond(String name): super(name);



}
Mixin Sample
class Security{



String name;



Security(this.name);



}
class TradeReporter{



String whereToReport;



reportMuniBondTrade(name){

print('Trade for municipal bond $name has been reported to $whereToReport');

}



reportCorpBondTrade(name){

print('Trade for corporate bond $name has been reported to $whereToReport');

}

}
class Stock extends Security{



String symbol;

double previousClosingPrice;



Stock(String name): super(name);



}
class Bond extends Security 

with TradeReporter{



double faceValue;

DateTime maturityDate;



Bond(String name): super(name);



}
A Mixin Sample
class Security{



String name;



Security(this.name);



}
class TradeReporter{



String whereToReport;



reportMuniBondTrade(name){

print('Trade for municipal bond $name has been reported to $whereToReport');

}



reportCorpBondTrade(name){

print('Trade for corporate bond $name has been reported to $whereToReport');

}

}
Bond bond = new Bond('Metropolitan Transportation');

bond.whereToReport = "SEC"; // from mixin

bond.reportMuniBondTrade('Metropolitan Transportation'); // from mixin
class Stock extends Security{



String symbol;

double previousClosingPrice;



Stock(String name): super(name);



}
Demo
Mixins
IDEA module: TradingMixins
Web Apps Development
<!DOCTYPE html>



<html>

<head>

<title>My Web App</title>

</head>



<body>

Your HTML content goes here


<script type="application/dart" src=“main.dart"></script>
</body>

</html>

For development with Dartium
<script data-pub-inline src="packages/browser/dart.js"></script>

Web Apps Deployment
<!DOCTYPE html>



<html>

<head>

<title>My Web App</title>

</head>



<body>

Your HTML content goes here


<script src=“main.dart.js"></script>

</body>

</html>
 For deployment, manually precompile you code with dart2js



or add a transformer to pubspec.yaml
dependencies:

browser: any

dart_to_js_script_rewriter: any

transformers:

- dart_to_js_script_rewriter
Running Dart Web App
1. From a command line:



Run pub serve and refresh the Web page
2. From IDEA: 



Right-click on your index.html file and run it in any Web
browser
Running Web app with pub serve
Running 

pub serve
Visiting

localhost:8080 

in Dartium
Visiting

localhost:8080 

in Chrome
Working with DOM in a Browser
<body>

Enter Symbol: :

<input id=“#enteredSymbol" type="text">





<script type="application/dart" src="main.dart"></script>

<script data-pub-inline src="packages/browser/dart.js"></script>

</body>
import 'dart:html';





void main() {



InputElement enteredSymbol = querySelector(“#enteredSymbol");
}

Event Handling
myHtmlElement.onChange.listen(myEventHandler);
void myEventHandler(Event e){

// Handle event here 

}
Element myHtmlElement = querySelector(“#myElementID");
A Simple Stock Quote Web App
<body>

Enter Symbol: :

<input id="enteredSymbol" type="text" placeholder="AAPL, IBM, or MSFT">



<span id="priceQuote"></span>



<script type="application/dart" src="main.dart"></script>

<script data-pub-inline src="packages/browser/dart.js"></script>

</body>
import 'dart:html';

import 'package:stock_quote_simple_web/stock.dart';

import 'package:stock_quote_simple_web/stock_quote_generator.dart';



StockQuoteGenerator generator = new StockQuoteGenerator();



InputElement enteredSymbol;

SpanElement priceQuote;



void main() {



enteredSymbol = querySelector(“#enteredSymbol");
priceQuote = querySelector(‘#priceQuote');


enteredSymbol.onChange.listen(showPrice); 

}



void showPrice(Event e){

Stock stock = generator.getQuote(enteredSymbol.value);

priceQuote.text = "$${stock.price.toStringAsFixed(2)}";

}
Event listener
Event handler
DOM search
Demo
Web app 

Working with DOM

Event Handling
IDEA module: StockQuoteSimpleWeb
name: stock_quote_simple_web

version: 0.0.1

description: >

An absolute bare-bones web app.

environment:

sdk: '>=1.0.0 <2.0.0'

dependencies:

browser: any

transformers:

- $dart2js:

commandLineOptions: [--minify, --show-package-warnings]
pubspec.yaml
Debugging Dart Web App
• In Chromium: 



- Open Chrome Development Tools, enable JavaScript sourcemaps



- Set breakpoints, refresh.
• In IntelliJ IDEA: 



- Install the extension JetBrains IDE Support in Chromium.



- Set the breakpoint in IDEA in Dart code and run your HTML file in the
debug mode.
Async Programming
• Use Future objects
• Use async and await keywords
Future, async, and await are for asynchronous execution.

For parallel execution use isolates.
Calling function Slow function
Callbackthen( );
Call
Future
Result
Async Processing: Futures
Async Processing: Futures
Calling function Slow function
Callbackthen( );
callingFunction(){



Future future = slowOperation("IBM");



future

.then((result){
// handle result here

});

}



slowOperation(stockSymbol){



return new Future.delayed(
const Duration(seconds: 10), () {

return "$stockSymbol is a great investment!";

});
}
Call
Future
Result
Error Handling in Future Objects
• A Future represents a deferred result of a function call.
• Register callbacks for success and errors:
doStuff()

.then(callbackForSuccess)

.catchError(callBackForError);
void callbackForSuccess() {

//...

}



void callbackForError(Error error){

// ...

}
Demo
Web app



Asyncronous processing using Future
IDEA module: StockQuoteFuture
Asynchronous Processing with async and await
• A function with async modifier
immediately returns a Future
• The code after await will wait for
the result
• You can have several sequential
operations with await
• The code flow is easier to read
comparing to callbacks, e.g. you
can place all awaits in the try/
catch block if need be.
callingFunction() async{



var result = await slowOperation(arg);

// the code will be suspended until 

// the result is returned


// Handle the result here 

}



slowOperation(stockSymbol){



return new Future.delayed(
const Duration(seconds: 10), () {

return "$stockSymbol is a great investment!";

});
}
Demo
Asyncronous processing using async
and await
IDEA module: StockQuoteAsyncAwait
AJAX:HttpRequest
var path = 'myData.json';



HttpRequest.getString(path)

.then((data) {

// do something with data

})

.catchError((Error error) {

print(error.toString());

});
The HttpRequest class from dart:html is used for AJAX operations 

from a Web browser:
The package http.dart can be used on both the client and server.
Demo
AJAX and JSON
IDEA module: StockQuoteWebJSON
Concurrency with Isolates
• Isolates are units of secure execution
• The code can only access classes/values located in the
same isolate
• Each isolate has its own heap - no shared memory
• The code in separate isolates can execute in parallel
• Isolates can communicate by sending each other
messages via send and receive ports
Isolates: Standalone vs Web Browser
Standalone Apps 



- run isolates in parallel
using available CPU
cores
- isolates can be created
by invoking spawn() or
spawnUri()
Web Browser Apps
- run isolates in Dart VM or
as JavaScript Web workers
- isolates can be created by
invoking spawnUri()
Isolates: Standalone vs Web Browser
Standalone Apps 



- run isolates in parallel
using available CPU
cores
- isolates can be created
by invoking spawn() or
spawnUri()
Web Browser Apps
- run isolates in Dart VM or
as JavaScript Web workers
- isolates can be created by
invoking spawnUri()
Use spawnUri() to dynamically load code
Demo
Parallel execution with isolates

Using multiple CPU cores
IDEA modules: IsolatesConsole and IsolatesWeb
Demo
1. Reading a large JSON file with HttpRequest - GUI doesn’t freeze
2. Running a long Dart loop with async - GUI freezes
3. Running a long Dart loop in isolate - GUI doesn’t freeze
IDEA module: FrozenAsyncOrIsolate
Dart-WebSocket-Java
Dart client’s getting data pushed by the GlassFish server:
main() {



var output = querySelector('#output');



WebSocket ws = new WebSocket(

'ws://localhost:8080/GlassfishWebsocketDart_war_exploded/clock');



ws.onOpen.listen((event){



output.text = "Connected";



});



ws.onMessage.listen((event){



output.text = event.data;



});



}
Java EE WebSocket Endpoint
@ServerEndpoint("/clock")

public class WebSocketClock {



static ScheduledExecutorService timer =

Executors.newSingleThreadScheduledExecutor();



private static Set<Session> allSessions;



DateTimeFormatter timeFormatter =

DateTimeFormatter.ofPattern("HH:mm:ss");

@OnOpen

public void showTime(Session session){

allSessions = session.getOpenSessions();



// start the scheduler on the very first connection

// to call sendTimeToAll every second

if (allSessions.size()==1){

timer.scheduleAtFixedRate(

() -> sendTimeToAll(session),0,1,TimeUnit.SECONDS);

}

}



private void sendTimeToAll(Session session){

allSessions = session.getOpenSessions();

for (Session sess: allSessions){

try{

sess.getBasicRemote().sendText("Local time: " +

LocalTime.now().format(timeFormatter));

} catch (IOException ioe) {

System.out.println(ioe.getMessage());

}

}

}

}
Demo
Pushing data from a Java EE server to
the Dart client using WebSocket protocol
IDEA module: GlassfishWebSocketDart
The detailed description of this demo is here: http://bit.ly/1DeulKX
Dart Tools
1. IDEs: Dart Editor, and plugins for all major IDEs
2. dart2js is a Dart-to-JavaScript transpiler and a tree-shaker
3. pub is a dependency management, development server and build tool.
4. gulp is a task manager. It’s an analog of Grunt or Gradle.
5. Dartium is a Web Browser for developers.
6. Dump-Info Visualizer allows to inspect the generated JavaScript.
7. Observatory is Dart profiler.
8. AngularDart is a port of AngularJS framework.
Links
• Code samples from this demo: https://github.com/Farata/dart
• Dart Style Guide https://www.dartlang.org/articles/style-guide
• Dart API docs: https://api.dartlang.org
• Try Dart: https://dartpad.dartlang.org
• Hands-on labs: darlang.org/codelabs
• List of languages that compile to JS: http://bit.ly/1FGHtPT
• NYC Dart meetup: http://www.meetup.com/Dart-Users-Group
More Links
• Our Dart/Java app: https://easy.insure
• Farata Systems: faratasystems.com
• Twitter: @yfain
• email: yfain@faratasystems.com
• Personal blog: yakovfain.com
• The book Java for Kids: 

http://yfain.github.io/Java4Kids/ 


More Related Content

What's hot

Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
Ran Mizrahi
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Zend Studio Tips and Tricks
Zend Studio Tips and TricksZend Studio Tips and Tricks
Zend Studio Tips and Tricks
Roy Ganor
 

What's hot (19)

Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
 
Developing Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJSDeveloping Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJS
 
Angular 2 - The Next Framework
Angular 2 - The Next FrameworkAngular 2 - The Next Framework
Angular 2 - The Next Framework
 
React native
React nativeReact native
React native
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Commit University - Exploring Angular 2
Commit University - Exploring Angular 2Commit University - Exploring Angular 2
Commit University - Exploring Angular 2
 
JavaFX Pitfalls
JavaFX PitfallsJavaFX Pitfalls
JavaFX Pitfalls
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
JavaFX Enterprise (JavaOne 2014)
JavaFX Enterprise (JavaOne 2014)JavaFX Enterprise (JavaOne 2014)
JavaFX Enterprise (JavaOne 2014)
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjects
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
 
Zend Studio Tips and Tricks
Zend Studio Tips and TricksZend Studio Tips and Tricks
Zend Studio Tips and Tricks
 
Android MvRx Framework 介紹
Android MvRx Framework 介紹Android MvRx Framework 介紹
Android MvRx Framework 介紹
 
Create Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien PotencierCreate Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien Potencier
 
Angular2 + rxjs
Angular2 + rxjsAngular2 + rxjs
Angular2 + rxjs
 
JavaOne - The JavaFX Community and Ecosystem
JavaOne - The JavaFX Community and EcosystemJavaOne - The JavaFX Community and Ecosystem
JavaOne - The JavaFX Community and Ecosystem
 
The JavaFX Ecosystem
The JavaFX EcosystemThe JavaFX Ecosystem
The JavaFX Ecosystem
 
Scaladays 2014 introduction to scalatest selenium dsl
Scaladays 2014   introduction to scalatest selenium dslScaladays 2014   introduction to scalatest selenium dsl
Scaladays 2014 introduction to scalatest selenium dsl
 
JavaFX in Action (devoxx'16)
JavaFX in Action (devoxx'16)JavaFX in Action (devoxx'16)
JavaFX in Action (devoxx'16)
 

Viewers also liked

Cours java smi 2007 2008
Cours java smi 2007 2008Cours java smi 2007 2008
Cours java smi 2007 2008
Khalil Lechheb
 
Java(ee) mongo db applications in the cloud
Java(ee) mongo db applications in the cloud Java(ee) mongo db applications in the cloud
Java(ee) mongo db applications in the cloud
Shekhar Gulati
 

Viewers also liked (17)

Cours java smi 2007 2008
Cours java smi 2007 2008Cours java smi 2007 2008
Cours java smi 2007 2008
 
Integrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business WorkflowIntegrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business Workflow
 
Introduction àJava
Introduction àJavaIntroduction àJava
Introduction àJava
 
Java(ee) mongo db applications in the cloud
Java(ee) mongo db applications in the cloud Java(ee) mongo db applications in the cloud
Java(ee) mongo db applications in the cloud
 
Bonnes pratiques des applications java prêtes pour la production
Bonnes pratiques des applications java prêtes pour la productionBonnes pratiques des applications java prêtes pour la production
Bonnes pratiques des applications java prêtes pour la production
 
Angular2 Development for Java developers
Angular2 Development for Java developersAngular2 Development for Java developers
Angular2 Development for Java developers
 
AngularJS for Java Developers
AngularJS for Java DevelopersAngularJS for Java Developers
AngularJS for Java Developers
 
RESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoTRESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoT
 
Reactive Thinking in Java
Reactive Thinking in JavaReactive Thinking in Java
Reactive Thinking in Java
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java Developers
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java Developers
 
Reactive programming in Angular 2
Reactive programming in Angular 2Reactive programming in Angular 2
Reactive programming in Angular 2
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
 
Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2
 
Building Universal Applications with Angular 2
Building Universal Applications with Angular 2Building Universal Applications with Angular 2
Building Universal Applications with Angular 2
 
Java 7 - Fork/Join
Java 7 - Fork/JoinJava 7 - Fork/Join
Java 7 - Fork/Join
 

Similar to Dart for Java Developers

CommissionCalculationbuildclasses.netbeans_automatic_build.docx
CommissionCalculationbuildclasses.netbeans_automatic_build.docxCommissionCalculationbuildclasses.netbeans_automatic_build.docx
CommissionCalculationbuildclasses.netbeans_automatic_build.docx
monicafrancis71118
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Code
erikmsp
 

Similar to Dart for Java Developers (20)

Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Dart Workshop
Dart WorkshopDart Workshop
Dart Workshop
 
Flex Maniacs 2007
Flex Maniacs 2007Flex Maniacs 2007
Flex Maniacs 2007
 
A First Date With Scala
A First Date With ScalaA First Date With Scala
A First Date With Scala
 
Domain Driven Design 101
Domain Driven Design 101Domain Driven Design 101
Domain Driven Design 101
 
Clean code
Clean codeClean code
Clean code
 
The Ring programming language version 1.5.4 book - Part 82 of 185
The Ring programming language version 1.5.4 book - Part 82 of 185The Ring programming language version 1.5.4 book - Part 82 of 185
The Ring programming language version 1.5.4 book - Part 82 of 185
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Bronx study jam 1
Bronx study jam 1Bronx study jam 1
Bronx study jam 1
 
CommissionCalculationbuildclasses.netbeans_automatic_build.docx
CommissionCalculationbuildclasses.netbeans_automatic_build.docxCommissionCalculationbuildclasses.netbeans_automatic_build.docx
CommissionCalculationbuildclasses.netbeans_automatic_build.docx
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Code
 
CSharp Advanced L05-Attributes+Reflection
CSharp Advanced L05-Attributes+ReflectionCSharp Advanced L05-Attributes+Reflection
CSharp Advanced L05-Attributes+Reflection
 
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
 
Annotation processor and compiler plugin
Annotation processor and compiler pluginAnnotation processor and compiler plugin
Annotation processor and compiler plugin
 
The Ring programming language version 1.5 book - Part 14 of 31
The Ring programming language version 1.5 book - Part 14 of 31The Ring programming language version 1.5 book - Part 14 of 31
The Ring programming language version 1.5 book - Part 14 of 31
 
The Ring programming language version 1.5.2 book - Part 79 of 181
The Ring programming language version 1.5.2 book - Part 79 of 181The Ring programming language version 1.5.2 book - Part 79 of 181
The Ring programming language version 1.5.2 book - Part 79 of 181
 
Java day 2016.pptx
Java day 2016.pptxJava day 2016.pptx
Java day 2016.pptx
 
Writing code that writes code - Nguyen Luong
Writing code that writes code - Nguyen LuongWriting code that writes code - Nguyen Luong
Writing code that writes code - Nguyen Luong
 

More from Yakov Fain

More from Yakov Fain (11)

Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020
 
Web sockets in Angular
Web sockets in AngularWeb sockets in Angular
Web sockets in Angular
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot apps
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot apps
 
Reactive Streams and RxJava2
Reactive Streams and RxJava2Reactive Streams and RxJava2
Reactive Streams and RxJava2
 
Using JHipster 4 for generating Angular/Spring Boot apps
Using JHipster 4 for generating Angular/Spring Boot appsUsing JHipster 4 for generating Angular/Spring Boot apps
Using JHipster 4 for generating Angular/Spring Boot apps
 
Java Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldJava Intro: Unit1. Hello World
Java Intro: Unit1. Hello World
 
Running a Virtual Company
Running a Virtual CompanyRunning a Virtual Company
Running a Virtual Company
 
Princeton jug git_github
Princeton jug git_githubPrinceton jug git_github
Princeton jug git_github
 
Surviving as a Professional Software Developer
Surviving as a Professional Software DeveloperSurviving as a Professional Software Developer
Surviving as a Professional Software Developer
 
Becoming a professional software developer
Becoming a professional software developerBecoming a professional software developer
Becoming a professional software developer
 

Recently uploaded

( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
nilamkumrai
 
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
nirzagarg
 
Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵
Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵
Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵
Chandigarh Call girls 9053900678 Call girls in Chandigarh
 
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
 
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
 
VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...
VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...
VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...
 
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
 
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
 
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
 
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
 
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
 
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort ServiceBusty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 
Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...
Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...
Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...
 
Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
 
Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...
Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...
Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...
 
Real Escorts in Al Nahda +971524965298 Dubai Escorts Service
Real Escorts in Al Nahda +971524965298 Dubai Escorts ServiceReal Escorts in Al Nahda +971524965298 Dubai Escorts Service
Real Escorts in Al Nahda +971524965298 Dubai Escorts Service
 
VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting High Prof...
VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting  High Prof...VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting  High Prof...
VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting High Prof...
 
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
 
Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵
Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵
Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵
 
Microsoft Azure Arc Customer Deck Microsoft
Microsoft Azure Arc Customer Deck MicrosoftMicrosoft Azure Arc Customer Deck Microsoft
Microsoft Azure Arc Customer Deck Microsoft
 
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
 

Dart for Java Developers

  • 1. © 2015 Farata Systems Dart for Java Developers Yakov Fain, Farata Systems
  • 2. Farata Systems and SuranceBay surancebay.comfaratasystems.com
  • 3. Our First Dart App: Easy Insure http://easy.insure
  • 4. Why Learn Google Dart • Dart is a productive way to develop future JavaScript apps today • Comes with a complete set of dev tools • Will help you to ease into the EcmaScript 6 developement in 2016
  • 5. Dart: Java Simplified • Program with classes and/or with functions • You can, but don’t have to declare variable types. • Any class is an interface • No data access qualifiers • Single-threaded but supports concurrency • No checked exceptions • No autoboxing/unboxing • IDEs: Dart Editor, IntelliJ IDEA, WebStorm, Eclipse Sublime Text… • Write in Dart and run either in Dart VM or as JavaScript on any browser
  • 6. Why Developing with Dart VM ? • Developing in Dart is more productive than in JavaScript. A static code analyser shows errors as you type. • Instanteneous feedback from the VM - no bytecode is generated for running in Dart VM. • During development there’s no need to transpile code to JS as in GWT. • Your program can run standalone in Dart VM. • Production deployment is done in JavaScript.
  • 7. The Dart App Entry Point A single entry point to any Dart app is a function main():
 main() {
 print('Hello world!');
 }
  • 8. The Dart App Entry Point A single entry point to any Dart app is a function main():
 main() {
 print('Hello world!');
 } Or with command-line arguments:
 import 'package:args/args.dart';
 
 main(List<String> args) {
 
 final parser = new ArgParser();
 argResults = parser.parse(args);
 
 List<String> someArgs = argResults.rest;
 
 print(‘Got the argument ${someArgs[0]}');
 
 }
  • 9. Checked Mode main() {
 print('Adding numbers: ${add (2,3)}');
 print('Adding strings: ${add ("Hello ","World")}');
 }
 
 add (num a, num b){
 
 return a+b;
 }
  • 10. Importing Packages • SDK comes with libraries whose names start with dart:
 
 • You can add packages in the directory packages of your project are app dependencies. Imports start with package: import 'dart:math'; import 'package:args/args.dart';
  • 11. Dart Libraries • dart:core • dart:async • dart:math • dart:io • dart:html • dart:mirrors • dart:convert
  • 12. Package Dependencies • Dart package manager is called pub • Dependencies are specified in the file pubspec.yaml. • Package versions are locked in the file pubspec.lock. name: stock_quote_console
 version: 0.0.1
 description: A stock quote app
 environment:
 sdk: '>=1.0.0 <2.0.0'
 dependencies:
 args: any
 dev_dependencies:
 unittest: any pubspec.yaml The central repo pub.dartlang.org has 1000+ packages 12
  • 13. Selected pub commands • pub get - retrieves packages (dependencies) • pub upgrade - upgrades packages and regenerates pubspec.lock • pub serve - starts dev http server • pub run - runs Dart scripts using dependencies from pubspec.yaml • pub build - generates and copies assets into the build dir • pub global - run Dart packages installed anywhere on the computer, pub.dartlang.org, or GitHub
  • 14. Demo Functions-only app 
 Using pub to get dependencies 
 Command-line arguments IDEA module: StockQuoteConsole
  • 15. Dart Classes • Name class files in small letters with _ as a word separator • Constructors support short syntax for variable initializations • No keywords for public, protected, private. • If a var name start with _ it’s private on a library level • No method overloading • Getters and setters are specified with get and set keywords
  • 16. Class Stock class Stock {
 String _symbol;
 double _price;
 
 Stock (this._symbol);
 
 double get price => _price==null?
 _price=getFromYahoo():_price;
 
 set price(double value){
 _price = value;
 }
 
 String get symbol => _symbol;
 
 set symbol(String value){ // some other processing may go here 
 _symbol = value;
 }
 } private vars constructor lazy getter setter
  • 17. Class Stock class Stock {
 String _symbol;
 double _price;
 
 Stock (this._symbol);
 
 double get price => _price==null?
 _price=getFromYahoo():_price;
 
 set price(double value){
 _price = value;
 }
 
 String get symbol => _symbol;
 
 set symbol(String value){
 _symbol = value;
 }
 } private vars constructor lazy getter setter Stock stock = new Stock("IBM"); 
 var price = stock.price;
  • 18. Constructors short form named optional param class Customer { 
 int _id;
 String name;
 
 Customer(this._id, this.name);
 
 Customer.taxExempt(int id, String name){
 // Do something lowering taxes
 } Customer.optName(this._id, {this.name});
 
 
 factory Customer.mafia(int id, String name){
 if (name == "Don Carleone") 
 return new Customer.taxExempt(id, name);
 else 
 return new Customer(id, name);
 }
 } factory
  • 19. Cascade Operator .. • Avoid repeating the object name • You can use method cascades .. on any object. • Every .. refers to the original object, not to the result of the previous method. querySelector('#abutton') // Get an object 
 ..text = 'Confirm' // Use its members
 ..classes.add('important')
 ..onClick.listen((e) => window.alert('Confirmed!'));
  • 20. Exceptions • All exceptions are unchecked • You can throw any objects: 
 
 throw “Something happened”; try {
 
 // Do stuff here
 
 } on NoSuchMethodError catch (e) {
 
 print(‘Error: ${e.stackTrace}');
 } on RangeError catch (e) {
 
 print(‘Error: ${e.stackTrace}');
 } on TypeError catch (e) {
 
 print(‘Error: ${e.stackTrace}');
 } catch (e) {
 
 print('$e');
 }
  • 22. Libraries library stock_quote;
 
 import 'dart:math';
 import 'dart:io';
 import 'package:args/args.dart';
 
 part "stock.dart";
 part "stock_quote_generator.dart";
 
 main(List<String> args) { … } part of stock_quote;
 
 class Stock { …
 } part of stock_quote;
 
 class StockQuoteGenerator {
 
 … } Combine classes and top-level functions into libraries.
  • 23. Demo • Classes • Getters • Setters • Libraries IDEA module: StockQuoteClassesConsole
  • 24. Mixins • Mixin is a class with functionality that can be added to another class using the with keyword • You can add multiple mixins to the class declaration class Bond extends Security with TradeReporter{ 
 } Java 8 interfaces are not mixins. They can’t have state.
  • 25. class Bond extends Security 
 with TradeReporter{ 
 double faceValue;
 DateTime maturityDate;
 
 Bond(String name): super(name);
 
 } Mixin Sample class Security{
 
 String name;
 
 Security(this.name);
 
 } class Stock extends Security{
 
 String symbol;
 double previousClosingPrice;
 
 Stock(String name): super(name);
 
 }
  • 26. class Bond extends Security 
 with TradeReporter{ 
 double faceValue;
 DateTime maturityDate;
 
 Bond(String name): super(name);
 
 } Mixin Sample class Security{
 
 String name;
 
 Security(this.name);
 
 } class TradeReporter{
 
 String whereToReport;
 
 reportMuniBondTrade(name){
 print('Trade for municipal bond $name has been reported to $whereToReport');
 }
 
 reportCorpBondTrade(name){
 print('Trade for corporate bond $name has been reported to $whereToReport');
 }
 } class Stock extends Security{
 
 String symbol;
 double previousClosingPrice;
 
 Stock(String name): super(name);
 
 }
  • 27. class Bond extends Security 
 with TradeReporter{
 
 double faceValue;
 DateTime maturityDate;
 
 Bond(String name): super(name);
 
 } A Mixin Sample class Security{
 
 String name;
 
 Security(this.name);
 
 } class TradeReporter{
 
 String whereToReport;
 
 reportMuniBondTrade(name){
 print('Trade for municipal bond $name has been reported to $whereToReport');
 }
 
 reportCorpBondTrade(name){
 print('Trade for corporate bond $name has been reported to $whereToReport');
 }
 } Bond bond = new Bond('Metropolitan Transportation');
 bond.whereToReport = "SEC"; // from mixin
 bond.reportMuniBondTrade('Metropolitan Transportation'); // from mixin class Stock extends Security{
 
 String symbol;
 double previousClosingPrice;
 
 Stock(String name): super(name);
 
 }
  • 29. Web Apps Development <!DOCTYPE html>
 
 <html>
 <head>
 <title>My Web App</title>
 </head>
 
 <body>
 Your HTML content goes here 
 <script type="application/dart" src=“main.dart"></script> </body>
 </html>
 For development with Dartium <script data-pub-inline src="packages/browser/dart.js"></script>

  • 30. Web Apps Deployment <!DOCTYPE html>
 
 <html>
 <head>
 <title>My Web App</title>
 </head>
 
 <body>
 Your HTML content goes here 
 <script src=“main.dart.js"></script>
 </body>
 </html>
 For deployment, manually precompile you code with dart2js
 
 or add a transformer to pubspec.yaml dependencies:
 browser: any
 dart_to_js_script_rewriter: any
 transformers:
 - dart_to_js_script_rewriter
  • 31. Running Dart Web App 1. From a command line:
 
 Run pub serve and refresh the Web page 2. From IDEA: 
 
 Right-click on your index.html file and run it in any Web browser
  • 32. Running Web app with pub serve Running 
 pub serve Visiting
 localhost:8080 
 in Dartium Visiting
 localhost:8080 
 in Chrome
  • 33. Working with DOM in a Browser <body>
 Enter Symbol: :
 <input id=“#enteredSymbol" type="text">
 
 
 <script type="application/dart" src="main.dart"></script>
 <script data-pub-inline src="packages/browser/dart.js"></script>
 </body> import 'dart:html';
 
 
 void main() {
 
 InputElement enteredSymbol = querySelector(“#enteredSymbol"); }

  • 34. Event Handling myHtmlElement.onChange.listen(myEventHandler); void myEventHandler(Event e){
 // Handle event here 
 } Element myHtmlElement = querySelector(“#myElementID");
  • 35. A Simple Stock Quote Web App <body>
 Enter Symbol: :
 <input id="enteredSymbol" type="text" placeholder="AAPL, IBM, or MSFT">
 
 <span id="priceQuote"></span>
 
 <script type="application/dart" src="main.dart"></script>
 <script data-pub-inline src="packages/browser/dart.js"></script>
 </body> import 'dart:html';
 import 'package:stock_quote_simple_web/stock.dart';
 import 'package:stock_quote_simple_web/stock_quote_generator.dart';
 
 StockQuoteGenerator generator = new StockQuoteGenerator();
 
 InputElement enteredSymbol;
 SpanElement priceQuote;
 
 void main() {
 
 enteredSymbol = querySelector(“#enteredSymbol"); priceQuote = querySelector(‘#priceQuote'); 
 enteredSymbol.onChange.listen(showPrice); 
 }
 
 void showPrice(Event e){
 Stock stock = generator.getQuote(enteredSymbol.value);
 priceQuote.text = "$${stock.price.toStringAsFixed(2)}";
 } Event listener Event handler DOM search
  • 36. Demo Web app 
 Working with DOM
 Event Handling IDEA module: StockQuoteSimpleWeb name: stock_quote_simple_web
 version: 0.0.1
 description: >
 An absolute bare-bones web app.
 environment:
 sdk: '>=1.0.0 <2.0.0'
 dependencies:
 browser: any
 transformers:
 - $dart2js:
 commandLineOptions: [--minify, --show-package-warnings] pubspec.yaml
  • 37. Debugging Dart Web App • In Chromium: 
 
 - Open Chrome Development Tools, enable JavaScript sourcemaps
 
 - Set breakpoints, refresh. • In IntelliJ IDEA: 
 
 - Install the extension JetBrains IDE Support in Chromium.
 
 - Set the breakpoint in IDEA in Dart code and run your HTML file in the debug mode.
  • 38. Async Programming • Use Future objects • Use async and await keywords Future, async, and await are for asynchronous execution.
 For parallel execution use isolates.
  • 39. Calling function Slow function Callbackthen( ); Call Future Result Async Processing: Futures
  • 40. Async Processing: Futures Calling function Slow function Callbackthen( ); callingFunction(){
 
 Future future = slowOperation("IBM");
 
 future
 .then((result){ // handle result here
 });
 }
 
 slowOperation(stockSymbol){
 
 return new Future.delayed( const Duration(seconds: 10), () {
 return "$stockSymbol is a great investment!";
 }); } Call Future Result
  • 41. Error Handling in Future Objects • A Future represents a deferred result of a function call. • Register callbacks for success and errors: doStuff()
 .then(callbackForSuccess)
 .catchError(callBackForError); void callbackForSuccess() {
 //...
 }
 
 void callbackForError(Error error){
 // ...
 }
  • 42. Demo Web app
 
 Asyncronous processing using Future IDEA module: StockQuoteFuture
  • 43. Asynchronous Processing with async and await • A function with async modifier immediately returns a Future • The code after await will wait for the result • You can have several sequential operations with await • The code flow is easier to read comparing to callbacks, e.g. you can place all awaits in the try/ catch block if need be. callingFunction() async{
 
 var result = await slowOperation(arg);
 // the code will be suspended until 
 // the result is returned 
 // Handle the result here 
 }
 
 slowOperation(stockSymbol){
 
 return new Future.delayed( const Duration(seconds: 10), () {
 return "$stockSymbol is a great investment!";
 }); }
  • 44. Demo Asyncronous processing using async and await IDEA module: StockQuoteAsyncAwait
  • 45. AJAX:HttpRequest var path = 'myData.json';
 
 HttpRequest.getString(path)
 .then((data) {
 // do something with data
 })
 .catchError((Error error) {
 print(error.toString());
 }); The HttpRequest class from dart:html is used for AJAX operations 
 from a Web browser: The package http.dart can be used on both the client and server.
  • 46. Demo AJAX and JSON IDEA module: StockQuoteWebJSON
  • 47. Concurrency with Isolates • Isolates are units of secure execution • The code can only access classes/values located in the same isolate • Each isolate has its own heap - no shared memory • The code in separate isolates can execute in parallel • Isolates can communicate by sending each other messages via send and receive ports
  • 48. Isolates: Standalone vs Web Browser Standalone Apps 
 
 - run isolates in parallel using available CPU cores - isolates can be created by invoking spawn() or spawnUri() Web Browser Apps - run isolates in Dart VM or as JavaScript Web workers - isolates can be created by invoking spawnUri()
  • 49. Isolates: Standalone vs Web Browser Standalone Apps 
 
 - run isolates in parallel using available CPU cores - isolates can be created by invoking spawn() or spawnUri() Web Browser Apps - run isolates in Dart VM or as JavaScript Web workers - isolates can be created by invoking spawnUri() Use spawnUri() to dynamically load code
  • 50. Demo Parallel execution with isolates
 Using multiple CPU cores IDEA modules: IsolatesConsole and IsolatesWeb
  • 51. Demo 1. Reading a large JSON file with HttpRequest - GUI doesn’t freeze 2. Running a long Dart loop with async - GUI freezes 3. Running a long Dart loop in isolate - GUI doesn’t freeze IDEA module: FrozenAsyncOrIsolate
  • 52. Dart-WebSocket-Java Dart client’s getting data pushed by the GlassFish server: main() {
 
 var output = querySelector('#output');
 
 WebSocket ws = new WebSocket(
 'ws://localhost:8080/GlassfishWebsocketDart_war_exploded/clock');
 
 ws.onOpen.listen((event){
 
 output.text = "Connected";
 
 });
 
 ws.onMessage.listen((event){
 
 output.text = event.data;
 
 });
 
 }
  • 53. Java EE WebSocket Endpoint @ServerEndpoint("/clock")
 public class WebSocketClock {
 
 static ScheduledExecutorService timer =
 Executors.newSingleThreadScheduledExecutor();
 
 private static Set<Session> allSessions;
 
 DateTimeFormatter timeFormatter =
 DateTimeFormatter.ofPattern("HH:mm:ss");
 @OnOpen
 public void showTime(Session session){
 allSessions = session.getOpenSessions();
 
 // start the scheduler on the very first connection
 // to call sendTimeToAll every second
 if (allSessions.size()==1){
 timer.scheduleAtFixedRate(
 () -> sendTimeToAll(session),0,1,TimeUnit.SECONDS);
 }
 }
 
 private void sendTimeToAll(Session session){
 allSessions = session.getOpenSessions();
 for (Session sess: allSessions){
 try{
 sess.getBasicRemote().sendText("Local time: " +
 LocalTime.now().format(timeFormatter));
 } catch (IOException ioe) {
 System.out.println(ioe.getMessage());
 }
 }
 }
 }
  • 54. Demo Pushing data from a Java EE server to the Dart client using WebSocket protocol IDEA module: GlassfishWebSocketDart The detailed description of this demo is here: http://bit.ly/1DeulKX
  • 55. Dart Tools 1. IDEs: Dart Editor, and plugins for all major IDEs 2. dart2js is a Dart-to-JavaScript transpiler and a tree-shaker 3. pub is a dependency management, development server and build tool. 4. gulp is a task manager. It’s an analog of Grunt or Gradle. 5. Dartium is a Web Browser for developers. 6. Dump-Info Visualizer allows to inspect the generated JavaScript. 7. Observatory is Dart profiler. 8. AngularDart is a port of AngularJS framework.
  • 56. Links • Code samples from this demo: https://github.com/Farata/dart • Dart Style Guide https://www.dartlang.org/articles/style-guide • Dart API docs: https://api.dartlang.org • Try Dart: https://dartpad.dartlang.org • Hands-on labs: darlang.org/codelabs • List of languages that compile to JS: http://bit.ly/1FGHtPT • NYC Dart meetup: http://www.meetup.com/Dart-Users-Group
  • 57. More Links • Our Dart/Java app: https://easy.insure • Farata Systems: faratasystems.com • Twitter: @yfain • email: yfain@faratasystems.com • Personal blog: yakovfain.com • The book Java for Kids: 
 http://yfain.github.io/Java4Kids/