Event driven javascript

870 views

Published on

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.

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

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

No notes for slide

Event driven javascript

  1. 1. Event Driven Javascriptfederico.galassi@cleancode.itslidehare.net/fgalassi
  2. 2. • Event driven programming• History of javascript design• Event driven javascript
  3. 3. Softwarecomponents exchangeinformation
  4. 4. Producers giveinformation
  5. 5. Consumers takeinformation
  6. 6. Taxonomy ofinteraction models
  7. 7. Who is theproducer ?
  8. 8. KnownWhere’s Kenny? Over There!
  9. 9. UnknownWhere’s Kenny? Over There! Where’s Kenny?
  10. 10. Who is theproducer ?known unknown
  11. 11. How doesinformation flow ?
  12. 12. PullWhere’s Kenny? Over There!
  13. 13. Push Let me know where’s Kenny Ok... later ...Hey! Over There!
  14. 14. How does information flow ? known unknownpullpush
  15. 15. 4 Models ofinteraction
  16. 16. 1. known unknown Requestpull Responsepush
  17. 17. Request Response//  method  invocationweapon  =  armory.buy(“shuriken”)kenny  =  cartman.findKenny()kenny.kill(weapon)
  18. 18. RequestResponse SIMPLE
  19. 19. RequestResponse SIMPLE SEQUENTIAL
  20. 20. RequestResponse SIMPLE SEQUENTIAL IMPERATIVE
  21. 21. RequestResponseHUMAN
  22. 22. Request Response TIGHTCOUPLING SEQUENTIAL IMPERATIVE
  23. 23. Request Response TIGHTCOUPLINGINEFFICIENT SEQUENTIAL IMPERATIVE
  24. 24. 2. known unknown Anonymous Requestpull Request Response Responsepush
  25. 25. AnonymousRequest Response The system decouplesinformation and its owner
  26. 26. AnonymousRequest Response load balancer
  27. 27. Anonymous Request Responsealancer FAILOVER
  28. 28. Anonymous Request Responsealancer FAILOVER EXTENSIBLE
  29. 29. Anonymous Request Response SYSTEMCOMPLEXITY
  30. 30. 3. known unknown Anonymous Requestpull Request Response Responsepush Callback
  31. 31. Callback//  observer  patterncartman.findKenny(    function(kenny)  {        kenny.kill(weapon)})
  32. 32. Don’t call usWe’ll call you
  33. 33. From Sequential COMPUTATIONINPUT OUTPUT STATE
  34. 34. To State MachineINPUT STATE A COMPUTATIONINPUT STATE B COMPUTATIONINPUT STATE C OUTPUT
  35. 35. CallbackRelinquish control
  36. 36. Callback Just in time is optimal ProducersConsumer
  37. 37. Callback efficiency
  38. 38. CallbackEXPLICIT efficiencyCONTROL FLOW
  39. 39. 4. known unknown Anonymous Requestpull Request Response Responsepush Callback Event Driven
  40. 40. Callback + AnonymousRequest Response = EVENTS
  41. 41. Home Automation Example
  42. 42. EVENTS FAILOVER + system COMPLEXITY +EXTENSIBLE + explicit efficiency = control flow =------------------------- ------------ ------------- ------------ ------------ power chaos
  43. 43. Expressive Power EVENTS ANON.CALLBACK REQUEST REQUEST RESPONSE RESPONSE
  44. 44. Complexity
  45. 45. Javascript isevent driven
  46. 46. NotJavascript Fault
  47. 47. NotYourFault
  48. 48. Just anHARDERproblem
  49. 49. • Event driven programming• History of javascript design• Event driven javascript
  50. 50. In the old days... Netscape Headquarters May 1995
  51. 51. This guy had two problems... Brendan Eich Creator of Javascript
  52. 52. 1. The world is Concurrent
  53. 53. ... and so is browser
  54. 54. User InputNetwork Requests
  55. 55. 2. Very very very short timeLiveScript first shipped in betas of Netscape Navigator 2.0 in September 1995
  56. 56. BePragmatic
  57. 57. He could useThreads ... Real preemptive concurrency
  58. 58. Threads are Evil
  59. 59. He could useCoroutines ... Emulated cooperative concurrency
  60. 60. needs acomplex scheduler
  61. 61. He was afunctional guy
  62. 62. Take it easyNot concurrentJust non-blocking
  63. 63. First class functions//  callbacks  give//  non  linear  executionwally.takeJob(function  work()  ...)wally.getCoffee(function  drink()  ...)//  ...  later  ...//  first  drink  coffee//  then  work
  64. 64. Simple event loop //  make  it  look  concurrent button.onclick(function()  { div.style.color  =  “red” }) UI UI update Click handlerevent UI update Click handlerqueue Click handlertime User click
  65. 65. Non-blocking I/O//  network  async  apixhr.onreadystatechange  =  function(){ ...})//  DOM  in  memorydiv.innerHTML  =  “Hello”
  66. 66. Javascript won
  67. 67. But sold its soulfor simplicity
  68. 68. One thread = Freeze
  69. 69. No Wait()
  70. 70. Simple sequentialfunction  breakfast()  { var  bacon  =  bacon() var  juice  =  orangeJuice() eat(bacon,  juice)} computationfunction  bacon()  { //  get  bacon return  bacon}
  71. 71. Async gets infunction  breakfast()  { var  bacon  =  bacon() wrong var  juice  =  orangeJuice() eat(bacon,  juice)}function  bacon()  { getBacon(function(bacon)  { //  got  bacon }) return what?}
  72. 72. Break computationfunction  breakfast()  {      var  callback  =  function(bacon)  { var  juice  =  getOrangeJuice() eat(bacon,  juice) } rest of computation bacon(callback)} computationfunction  bacon(callback)  { //  get  bacon  async callback(bacon)}
  73. 73. Break morefunction  breakfast()  {      var  callback  =  function(bacon)  { var  callback  =  function(juice)  { eat(bacon,  juice) rest of computation 2 } getOrangeJuice(callback) } rest of computation 1 bacon(callback)} computation
  74. 74. Continuation Passing Style
  75. 75. it’s Viral 1//  simple  sequential  computationfunction  A()  {  return  B()  }function  B()  {  return  C()  }function  C()  {  return  value  }A()
  76. 76. it’s Viral 2//  C  becomes  async,  everything  becomes  asyncfunction  A(callback)  { B(function(value)  {  callback(value)  })}function  B(callback)  { C(function(value)  {  callback(value)  })}function  C(callback)  {  callback(value)  }A()
  77. 77. it’s Hard sleep//  simple  sequential  sleepsleep(3000)doSomething()
  78. 78. it’s Hard sleep//  not  so  simple  sleepsetTimeout(function()  { doSomething()},  3000)
  79. 79. it’s Hard loop//  simple  sequential  loopimages.forEach(function(url) var  image  =  fetchImage(url) image.show()}
  80. 80. it’s Hard loop//  fetchImage  is  asyncimages.forEach(function(url) fetchImage(url,  function(image)  { image.show() })}
  81. 81. it’s Hard loop//  Show  them  in  the  right  orderfunction  processImage()  { var  url  =  images.shift() if  (url)  { fetchImage(url,  function(image)  { image.show() processImage() }) }}processImage()
  82. 82. Javascript sacrificedconveniencefor simplicity
  83. 83. ... and it was the right choice
  84. 84. • Event driven programming• History of javascript design• Event driven javascript
  85. 85. How can we tamecomplexity?
  86. 86. AddWait()stupid!
  87. 87. Easy sleep//  simple  sequential  sleep  with  wait/resumesleep(3000)doSomething()function  sleep(msec)  { wait( setTimeout(function()  { resume() },  msec) )}
  88. 88. Beautiful
  89. 89. Already done !
  90. 90. //  write  sequential  logicfunction  doOpsABC()  { waitfor  { var  x  =  doOpA() } and  { var  y  =  doOpB() } return  doOpC(x,y)} http://stratifiedjs.org/
  91. 91. Transform tocontinuation passing style
  92. 92. //  synchronous  readfs.read(path).wait() http://nodejs.org/
  93. 93. Implementcoroutines
  94. 94. Back tocomplexity
  95. 95. Jeremy Ashkenas - CoffeeScript “Case in point, Stratified JS: A virtuoso performance of JavaScript compilation, but look at what it compiles into.” “I dont think we want to take CoffeeScript down that path. Open the Pandoras box of injecting special functions into the runtime, and ... suddenly you have to worry about being orders of magnitude slower than normal JS.” https://github.com/jashkenas/coffee-script/issuesearch?state=closed&q=asynchronous#issue/350/comment/330116
  96. 96. Jeremy Ashkenas - CoffeeScriptvar getDocument = function(){ var getDocument; waitfor(document) { __oni_rt.exec(__oni_rt.Seq(0,__oni_rt.Seq(0,__oni_rt.Nblock( resume(db.get(id)); function(arguments){ } getDocument=function (){ return document; 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.Nbl 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);
  97. 97. Ryan Dahl - node.js “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 Im trying to avoid in Node.” http://groups.google.com/group/nodejs/msg/df199d233ff17efa
  98. 98. Take it easy No wait()Just flow control
  99. 99. Sequence 1//  async  sequential  computationsequence(get,  filter,  process)function  get(resume)  { $.get(url,  function(data)  { resume(data) })}function  filter(resume,  data)  {  ...  }function  process(resume,  data)  {  ...  }
  100. 100. Sequence 2//  async  sequential  computationfunction  sequence()  { var  steps  =  arguments.slice() var  doStep  =  function(val)  { var  next  =  steps.shift() if  (next)  { next.apply(null,  [doStep,  val]) } } doStep()}
  101. 101. Functional programmingfirst(fetchA,  fetchB,  fetchC)every(checkA,  checkB,  checkC)map(array,  mapper)filter(array,  filter)
  102. 102. From imperativevar  clicks  =  0,  timeout  =  null$(“button”).click(function()  { clicks++ if  (clicks  ==  1)  { timeout  =  setTimeout(function()  { clicks  ==  0 }) } if  (clicks  ==  3)  { clearTimeout(timeout) clicks  =  0 $(this).trigger(“tripleclick”) }})
  103. 103. To declarative$(button) .on(“click”) .times(3) .within(“1  second”) .trigger(“tripleclick”)
  104. 104. Questions?
  105. 105. federico.galassi@cleancode.it

×