event driven javascript

106
Event Driven Javascript [email protected] slidehare.net/fgalassi

Upload: federico-galassi

Post on 26-May-2015

9.840 views

Category:

Technology


0 download

DESCRIPTION

Talk i gave at WebTech Conference on November 10th 2010. Abstract: Why is web application programming so difficult? Is it javascript fault? Is it our fault? Time to take the red pill and wake up in the real, event driven world. A world where if you can dodge the bullets of skyrocketing complexity, your programs can be made scalable, fault tolerant, extensible and just beautiful. Also http://federico.galassi.net/ http://www.webtechcon.it Follow me on Twitter! https://twitter.com/federicogalassi

TRANSCRIPT

Page 2: Event Driven Javascript

• Event driven programming

• Event driven javascript• History of javascript design

Page 3: Event Driven Javascript

Software components

exchangeinformation

Page 4: Event Driven Javascript

Producersgive

information

Page 5: Event Driven Javascript

Consumerstake

information

Page 6: Event Driven Javascript

Taxonomy ofinteraction models

Page 7: Event Driven Javascript

Who is the producer ?

Page 8: Event Driven Javascript

KnownWhere’s Kenny?

Over There!

Page 9: Event Driven Javascript

UnknownWhere’s Kenny?

Where’s Kenny?

Over There!

Page 10: Event Driven Javascript

Who is the producer ?known unknown

Page 11: Event Driven Javascript

How does information flow ?

Page 12: Event Driven Javascript

PullWhere’s Kenny?

Over There!

Page 13: Event Driven Javascript

PushLet me know

where’s Kenny

Ok

... later ...Hey! Over There!

Page 14: Event Driven Javascript

How does information flow ?

known unknownpull

push

Page 15: Event Driven Javascript

4 Models ofinteraction

Page 16: Event Driven Javascript

known unknown

pull

push

RequestResponse

1.

Page 17: Event Driven Javascript

Request Response

//  method  invocationweapon  =  armory.buy(“shuriken”)kenny  =  cartman.findKenny()kenny.kill(weapon)

Page 18: Event Driven Javascript

SIMPLE

Request Response

Page 19: Event Driven Javascript

SIMPLESEQUENTIAL

Request Response

Page 20: Event Driven Javascript

SIMPLESEQUENTIAL

IMPERATIVE

Request Response

Page 21: Event Driven Javascript

HUMAN

Request Response

Page 22: Event Driven Javascript

SEQUENTIALIMPERATIVE

Request Response

TIGHT COUPLING

Page 23: Event Driven Javascript

SEQUENTIALIMPERATIVE

Request Response

TIGHT COUPLING

INEFFICIENT

Page 24: Event Driven Javascript

known unknown

pull

push

RequestResponse

2.

AnonymousRequest

Response

Page 25: Event Driven Javascript

AnonymousRequest Response

The system decouplesinformation and its owner

Page 26: Event Driven Javascript

AnonymousRequest Response

load balancer

Page 27: Event Driven Javascript

AnonymousRequest Response

FAILOVERload balancer

Page 28: Event Driven Javascript

AnonymousRequest Response

load balancer FAILOVER

EXTENSIBLE

Page 29: Event Driven Javascript

AnonymousRequest Response

SYSTEMCOMPLEXITY

Page 30: Event Driven Javascript

known unknown

pull

push

RequestResponse

3.

AnonymousRequest

Response

Callback

Page 31: Event Driven Javascript

Callback

//  observer  patterncartman.findKenny(    function(kenny)  {        kenny.kill(weapon)})

Page 32: Event Driven Javascript

Don’t call usWe’ll call you

Page 33: Event Driven Javascript

From Sequential

INPUT

STATE

COMPUTATION

OUTPUT

Page 34: Event Driven Javascript

To State MachineINPUT STATE A

OUTPUT

INPUT STATE B

INPUT STATE C

COMPUTATION

COMPUTATION

Page 35: Event Driven Javascript

Callback

Relinquish control

Page 36: Event Driven Javascript

Just in time is optimal

Callback

Consumer

Producers

Page 37: Event Driven Javascript

Callback

efficiency

Page 38: Event Driven Javascript

Callback

efficiencyEXPLICITCONTROL

FLOW

Page 39: Event Driven Javascript

known unknown

pull

push

RequestResponse

4.

AnonymousRequest

Response

Callback Event Driven

Page 40: Event Driven Javascript

Callback +Anonymous

Request Response=

EVENTS

Page 41: Event Driven Javascript

Home AutomationExample

Page 42: Event Driven Javascript

EVENTS

FAILOVER +EXTENSIBLE +efficiency =-------------------------------------

power

systemCOMPLEXITY +

explicitcontrol flow =-------------------------------------chaos

Page 43: Event Driven Javascript

REQUEST RESPONSECALLBACK

ANON.REQUEST

RESPONSE

EVENTS

Expressive Power

Page 44: Event Driven Javascript

Complexity

Page 45: Event Driven Javascript

Javascriptis

event* driven

* technically callback driven

Page 46: Event Driven Javascript

NotJavascript

Fault

Page 47: Event Driven Javascript

NotYourFault

Page 48: Event Driven Javascript

Just anHARDER

problem

Page 49: Event Driven Javascript

• Event driven programming

• Event driven javascript• History of javascript design

Page 50: Event Driven Javascript

In the old days...

Netscape HeadquartersMay 1995

Page 51: Event Driven Javascript

This guy had two problems...

Brendan EichCreator of Javascript

Page 52: Event Driven Javascript

1. The world isConcurrent

Page 53: Event Driven Javascript

... and so isbrowser

Page 54: Event Driven Javascript

Network RequestsUser Input

Page 55: Event Driven Javascript

LiveScript first shipped in betas of Netscape Navigator 2.0 inSeptember 1995

2. Very very veryshort time

Page 56: Event Driven Javascript

BePragmatic

Page 57: Event Driven Javascript

He could use

Threads ...Real preemptive

concurrency

Page 58: Event Driven Javascript

ThreadsareEvil

Page 59: Event Driven Javascript

He could use

Coroutines ...Emulated

cooperativeconcurrency

Page 60: Event Driven Javascript

needs acomplex

scheduler

Page 61: Event Driven Javascript

He was afunctional

guy

Page 62: Event Driven Javascript

Not concurrent

Take it easy

Just non-blocking

Page 63: Event Driven Javascript

Callbacks//  callbacks  give//  non  linear  executionwally.takeJob(function  work()  ...)wally.getCoffee(function  drink()  ...)

//  ...  later  ...//  first  drink  coffee//  then  work

Page 64: Event Driven Javascript

Simple event loop//  make  it  look  concurrentbutton.onclick(function()  {...

})

UI update

Click handler

UI update

Click handler

Click handlerUI

eventqueue

timeUser click

Page 65: Event Driven Javascript

Non-blocking I/O//  network  async  apixhr.onreadystatechange  =  function(){...

})

//  DOM  manipulations  are  synchronous//  but  in  memory  so  very  fastdiv.innerHTML  =  “Hello”

Page 66: Event Driven Javascript

Javascript won

Page 67: Event Driven Javascript

Butsold its soul

for simplicity

Page 68: Event Driven Javascript

One thread=

Freeze

Page 69: Event Driven Javascript

No Wait()

Page 70: Event Driven Javascript

function  breakfast()  {var  bacon  =  bacon()var  juice  =  orangeJuice()eat(bacon,  juice)

}

Simple sequential

function  bacon()  {//  get  baconreturn  bacon

}

computation

Page 71: Event Driven Javascript

function  breakfast()  {var  bacon  =  bacon()var  juice  =  orangeJuice()eat(bacon,  juice)

}

function  bacon()  {getBacon(function(bacon)  {

//  got  bacon})

}

Async gets inwrong

return what?

Page 72: Event Driven Javascript

Break computationfunction  breakfast()  {      var  callback  =  function(bacon)  {

var  juice  =  getOrangeJuice()eat(bacon,  juice)

}bacon(callback)

}

function  bacon(callback)  {//  get  bacon  asynccallback(bacon)

}

rest of computation

computation

Page 73: Event Driven Javascript

Break morefunction  breakfast()  {      var  callback  =  function(bacon)  {

var  callback  =  function(juice)  {eat(bacon,  juice)

}getOrangeJuice(callback)

}bacon(callback)

}

rest of computation 1

computation

rest of computation 2

Page 74: Event Driven Javascript

ContinuationPassing

Style

Page 75: Event Driven Javascript

//  simple  sequential  computation

function  A()  {  return  B()  }function  B()  {  return  C()  }function  C()  {  return  value  }

A()

it’s Viral 1

Page 76: Event Driven Javascript

it’s Viral //  C  becomes  async,  everything  becomes  async

function  A(callback)  {B(function(value)  {  callback(value)  })

}function  B(callback)  {

C(function(value)  {  callback(value)  })}function  C(callback)  {  callback(value)  }

A()

2

Page 77: Event Driven Javascript

//  simple  sequential  sleep

sleep(3000)doSomething()

sleepit’s Hard

Page 78: Event Driven Javascript

//  not  so  simple  sleep

setTimeout(function()  {doSomething()

},  3000)

sleepit’s Hard

Page 79: Event Driven Javascript

//  simple  sequential  loop

images.forEach(function(url)var  image  =  fetchImage(url)image.show()

}

loopit’s Hard

Page 80: Event Driven Javascript

//  fetchImage  is  async

images.forEach(function(url)fetchImage(url,  function(image)  {

image.show()})

}

loopit’s Hard

Page 81: Event Driven Javascript

//  Show  them  in  the  right  order

function  processImage()  {var  url  =  images.shift()if  (url)  {

fetchImage(url,  function(image)  {image.show()processImage()

})}

}processImage()

loopit’s Hard

Page 82: Event Driven Javascript

Javascriptsacrificed

conveniencefor simplicity

Page 83: Event Driven Javascript

... and it was the right choice

Page 84: Event Driven Javascript

• Event driven programming

• Event driven javascript• History of javascript design

Page 85: Event Driven Javascript

How can we tame

complexity?

Page 86: Event Driven Javascript

AddWait()

stupid!

Page 87: Event Driven Javascript

Easy//  simple  sequential  sleep  with  wait/resume

sleep(3000)doSomething()

function  sleep(msec)  {wait(

setTimeout(function()  {resume()

},  msec))

}

sleep

Page 88: Event Driven Javascript

Beautiful

Page 89: Event Driven Javascript

Already done !

Page 90: Event Driven Javascript

http://stratifiedjs.org/

//  write  sequential  logic

function  doOpsABC()  {waitfor  {

var  x  =  doOpA()}and  {

var  y  =  doOpB()}return  doOpC(x,y)

}

Page 91: Event Driven Javascript

Transform tocontinuation

passingstyle

Page 92: Event Driven Javascript

http://nodejs.org/

//  synchronous  read

fs.read(path).wait()

Page 93: Event Driven Javascript

Implementcoroutines

Page 94: Event Driven Javascript

Back tocomplexity

Page 95: Event Driven Javascript

Jeremy Ashkenas - CoffeeScript

“I don't think we want to take CoffeeScript down that path. Open the Pandora's box of injecting special functions into the runtime, and ... suddenly you have to worry about being orders of magnitude slower than normal JS.”

“Case in point, Stratified JS: A virtuoso performance of JavaScript compilation, but look at what it compiles into.”

https://github.com/jashkenas/coffee-script/issuesearch?state=closed&q=asynchronous#issue/350/comment/330116

Page 96: Event Driven Javascript

Jeremy Ashkenas - CoffeeScript

var getDocument = function(){ waitfor(document) { resume(db.get(id)); } return document; };

var getDocument;__oni_rt.exec(__oni_rt.Seq(0,__oni_rt.Seq(0,__oni_rt.Nblock(function(arguments){ getDocument=function (){ return __oni_rt.exec(__oni_rt.Seq(1,__oni_rt.Suspend( function(arguments, resume){ return __oni_rt.exec(__oni_rt.Seq(0,__oni_rt.Fcall(0,__oni_rt.Nblock( function(arguments){ return resume; }),__oni_rt.Nblock(function(arguments){ return db.get(id) }) )),arguments,this)}, function() { document=arguments[0]; }),__oni_rt.Fcall(0,__oni_rt.Return,__oni_rt.Nblock( function(arguments){ return document; }) )),arguments, this)};}))), this.arguments, this);

Page 97: Event Driven Javascript

“I will be removing wait() in the next release of Node.It has already been removed from the documentation.”

“A proper implementation of wait() necessitates true coroutines”

“This sort of mental complication is exactly what I'm trying to avoid in Node.”

Ryan Dahl - node.js

http://groups.google.com/group/nodejs/msg/df199d233ff17efa

Page 98: Event Driven Javascript

No wait()

Take it easy

Just control flow

Page 99: Event Driven Javascript

Sequence//  async  sequential  computationsequence(get,  filter,  process)

function  get(resume)  {$.get(url,  function(data)  {

resume(data)})

}

function  filter(resume,  data)  {  ...  }function  process(resume,  data)  {  ...  }

1

Page 100: Event Driven Javascript

Sequence//  async  sequential  computation

function  sequence()  {var  steps  =  arguments.slice()var  doStep  =  function(val)  {

var  next  =  steps.shift()if  (next)  {

next.apply(null,  [doStep,  val])}

}doStep()

}

2

Page 101: Event Driven Javascript

Functional programming

first(fetchA,  fetchB,  fetchC,  callback)every(checkA,  checkB,  checkC,  callback)map(array,  mapper,  callback)filter(array,  filter,  callback)

Page 102: Event Driven Javascript

The road is

taking yourcontrol flow

Page 103: Event Driven Javascript

From imperative//  complex  triple  click  event

var  clicks  =  0,  timeout  =  null

$(“button”).click(function()  {clicks++if  (clicks  ==  1)  {

timeout  =  setTimeout(function()  {clicks  =  0

},  1000)}if  (clicks  ==  3)  {

clearTimeout(timeout)clicks  =  0$(this).trigger(“tripleclick”)

}})

Page 104: Event Driven Javascript

To declarative$(button).on(“click”).times(3).within(“1  second”).trigger(“tripleclick”)

Page 105: Event Driven Javascript

Questions?