Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Types and Immutability: why you should care

603 views

Published on

Data types. Type checking. IO data parsing. Immutability. Persistent data structures. Immutable languages.

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Types and Immutability: why you should care

  1. 1. why you should care @jcemer Types and Immutability
  2. 2. @jcemer
 jcemer.com
  3. 3. 2012 - Event-driven Programming
 2012 - CoffeeScript 2013 - OO and Functional Programming 2014 - Async Control Flow 2015 - Modern Paradigms and Concepts 2017 - Managing and Evolving Code 2017 - Types and Immutability
  4. 4. JavaScript is a high- level, dynamic, weakly typed, object-based, 
 multi-paradigm, and
 interpreted language  According Wikipedia
  5. 5. 01Data Types
  6. 6. A type is a set of similar values with associated operations
  7. 7. 4 2.1 893 12 2.3 5.3 * 56 1 3 4 6 9.4
  8. 8. ObjectString Number Undefined Null Boolean Symbol Literal Array Function Date JSON … Primitives
  9. 9. undefined?
  10. 10. Types in JavaScript have always been a headache
  11. 11. class Product { constructor (name, cost, tax) { this.name = name this.cost = cost this.tax = tax } price() { return this.cost * 
 (1 + this.tax) } } Product Name Cost Tax Price() String Number Number Number
  12. 12. const item = new Product("Banana", 2, "%30") item.price() this.name = name this.cost = cost this.tax = tax } price() { return this.cost * 
 (1 + this.tax) } } This is Not 
 a Number™
  13. 13. There is a typo here! const item = new Product("Banana", 2, .3) item.prices() this.name = name this.cost = cost this.tax = tax } price() { return this.cost * 
 (1 + this.tax) } }
  14. 14. Modern
 errors
  15. 15. The new keyword is missing
  16. 16. Common Mistake #1:
 Incorrect references to this The 10 Most Common Mistakes JavaScript Developers Make 
 by Ryan J. Peterson
  17. 17. function Product(name, cost, tax) { if (!(this instanceof Product)) { throw new Error("Constructor called as a function") } this.name = name this.cost = cost this.tax = tax } Product("Banana", 2, "%30")
  18. 18. 1 * 'foo' 'foo' * 1 'foo' + 1 [] + {} ({}) + {} null + 1 5 % undefined null.prop undefined()
  19. 19. 1. NaN 2. undefined is not a function 3. incorrect this reference 4. cannot read/set any property of undefined/null 5. silent errors
  20. 20. Those are all typical examples of runtime errors from a dynamic language
  21. 21. 02Type Checking
  22. 22. flow.org
  23. 23. Static type checking is performed before running code
  24. 24. eslint.org
  25. 25. Let’s add types to help programmers and not computers
  26. 26. Product Name Cost Tax Price() String Number Number Number
  27. 27. /* @flow */ class Product { name: string cost: number tax: number constructor (name, cost, tax) { this.name = name this.cost = cost this.tax = tax } price() { return this.cost * (1 + this.tax) } } const item = new Product("Banana", 2, "%30") Type annotations Type incompatible!
  28. 28. typescript
 lang.org
  29. 29. primitives
 objects (arrays, classes, …)
 literal + Types
  30. 30. any 
 nullable or maybe 
 union and intersection + Advanced Types Any value null or Product Product or FreeProduct
  31. 31. new types (aliases) 
 interfaces 
 generics + Fancy Types Cost is a number Any value with price method “a way of abstracting a type away”
  32. 32. Type Signature allows you to foresee problems Types as Design Tools 
 by Kris Jenkins
  33. 33. /* @flow */ function crazy() : number | string | Array<null> { const rand = Math.random() if (rand > .5) { return 0 } if (rand < .5) { return [] } return rand.toString() } const ops : number | string | Array<null> = crazy() Type smells!
  34. 34. A Type System is, first and foremost, 
 a communication mechanism Tweet by Sarah Mei
  35. 35. A Type System replaces direct communication with other humans, when such communication isn't practical - large teams, open source, etc Tweet by Sarah Mei
  36. 36. 03IO Data Parsing
  37. 37. interface ItemsResponse { results: string[] } http.get<ItemsResponse>('/api/items') .subscribe(data => { this.results = data.results }) It should return a result property with an array of strings from Angular documentation
  38. 38. interface ItemsResponse { results: string[] } { "results": [ "Item 1", "Item 2", ] } Code API Responses { "results": [ 8, 4, ] } Oops!
  39. 39. Trust me, 
 I'm an 
 engineer
  40. 40. /* @flow */ const someValue: any = null const strLength: number = someValue.length any is a 
 bad guy!
  41. 41. Using any is completely unsafe, and should be avoided whenever possible from Flow documentation
  42. 42. Runtime exception: the case of broken data not being handled
  43. 43. elm-lang.org
  44. 44. Elm is a statically typed language with no runtime exceptions
  45. 45. type alias Product = { name : String , cost : Float , tax : Float } price : Product -> Float price {cost,tax} = cost * (tax + 1) Almost only type annotation
  46. 46. item : Product item = { name = "Banana", cost = 2, tax = 0.3 } itemPrice : Float itemPrice = price item -- 2.6 : Float type alias Product = { name : String , cost : Float , tax : Float } price : Product -> Float price {cost,tax} = cost * (tax + 1)
  47. 47. > import Json.Decode exposing (..) > resultsDecoder = field "results" (list string) > decodeString resultsDecoder "bla" Err "Given an invalid JSON: Unexpected token b in JSON…" : Result.Result String (List String) > decodeString resultsDecoder "{ "results": ["1", "2"] }" Ok ["1","2"] : Result.Result String (List String)
  48. 48. Request Response Ok Render results Show an error 
 message Err
  49. 49. A Result wraps any computation that may fail, this is a great way to manage errors Elm documentation
  50. 50. There is no exception in Elm, the code must cover all edge cases
  51. 51. Relax, you don’t need to move away from JavaScript!
  52. 52. var t = require("tcomb") const Results = t.interface({ results: t.list(t.String) }, "Results") Results({ results: ["1", "2"] }) Results({ results: [2] }) // TypeError: [tcomb] Invalid value 2 supplied to Results/ results: Array<String>/0: String Check the types values 
 at runtime  github.com/
 gcanti/tcomb
  53. 53. + github.com/ gcanti/
 babel-plugin- tcomb
  54. 54. bit.ly/
 runtime-type- validation +
  55. 55. We should focus our efforts on either avoiding —or fixing!—the corner case value coercions Fixing Coercion, Not The Symptoms by Kyle Simpson
  56. 56. 04Immuta bility
  57. 57. All JavaScript primitives are immutable
  58. 58. But JavaScript objects are mutable
  59. 59. Oops! Side effects
  60. 60. User Product Data model UI components user.father.name = "Peter" X X X X X X X X Father Mother … … …
  61. 61. A small change on mutable data implies on check and render all descendants components
  62. 62. No way to watch 
 changes! 🙏
  63. 63. Immutability is a very good paradigm
  64. 64. Immutable data just is, once created, it will be the same forever
  65. 65. const newUser = { ...user, father: { ...user.father, name: "Peter" } } Create a new user with a new father user === newUser // false user.father === newUser.father // false user.name === newUser.name // true user.mother === newUser.mother // true
  66. 66. UI components Re-render user === newUser 
 // false product === newProduct 
 // true No re-render
  67. 67. Immutable 
 data removes complexity Immutable Data and React 
 by Lee Byron
  68. 68. Immutability improve performance when used with React Pure Component or Angular OnPush Change Detection
  69. 69. redux.js.org
 
 github.com/
 jcemer/ minimalistic- shop
  70. 70. Oops
  71. 71. const item = [0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, …]
  72. 72. // item.push(42) without mutation: var itemNew = item.concat([42]) // item.unshift(42) without mutation: var itemNew = [42].concat(item) // item[10] = 42 without mutation: var itemNew = item.slice(0, 10)
 .concat(42)
 .concat(item.slice(11)) // item.splice(10, 0, 42) without mutation: var itemNew = item.slice(0, 10)
 .concat(42)
 .concat(item.slice(10)) Ok,
 Enough is enough!
  73. 73. Array manipulation is very optimized when performed with mutation
  74. 74. 05 Persistent data structures
  75. 75. facebook.
 github.io/ immutable-js/
  76. 76. Think about managing the data like code on Git Immutable data structures for functional JS by Anjana Vakil
  77. 77. const item = Immutable.List(
 [0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, …] ) const item2 = item.push(42) const item3 = item.unshift(42) const item4 = item.set(10, 42) const item5 = item.insert(10, 42)
  78. 78. Hash Array Mapped Trie
  79. 79. Immutable Data and React Immutable data structures for functional JS youtu.be/Wo0qiGPSV-s youtu.be/I7IdS-PbEgI
  80. 80. const user = { name: "Paul", father: { name: "John" }, mother: { name: "Ana" } } const item = Immutable.fromJS(user) const newItem = item.setIn(
 ["father", "name"], "Peter"
 ) Deep change
  81. 81. ImmutableJS has poor docs, hard debugging and enforces a new API for data manipulation
  82. 82. redux.js.org/ docs/
 recipes/ UsingImmutableJ S.html
  83. 83. 06Immutable languages
  84. 84. All values in Elm are immutable According Wikipedia 🤔
  85. 85. There are many tools and languages nowadays that enforce Pure Functional Paradigm
  86. 86. staltz.com/
 is-your-javascript- function-actually- pure.html
  87. 87. It’s an incredible blessing, that we went from 0 viable ways to do FP in the browser to 4 in just a few years JavaScript vs Elm vs PureScript vs GHCjs vs Scalajs by Isaac Shapira
  88. 88. ***
  89. 89. I hope you learned something new! @jcemer Thank you
  90. 90. Special thanks Hugo Bessa Rafael Rinaldi Rodrigo Willrich Zeh Fernandes Marcelo Boeira Felipe Fialho Rachel Mason

×