Connect.Tech 2019: Solving the Boolean Identity Crisis

Connect.Tech 2019: Solving the Boolean Identity Crisis

While powerful in its simplicity and important to computation, the boolean can be limiting in applications. In this talk, briefly explore the history of boolean logic in computation and look at how booleans can become misused. See examples where booleans obscure the meaning of code, make code harder to maintain, and hinder usability for your teammates and users. You will learn how to harness techniques from functional programming languages in the world of JavaScript to write clearer code. Most importantly, you will learn how to place usability at the forefront of the APIs and UIs you build.

94bd558238b69c45d3d3e15797ae94f7?s=128

Jeremy Fairbank

October 17, 2019
Tweet

Transcript

  1. Jeremy Fairbank @elpapapollo

  2. @testdouble helps improves how the world build software. testdouble.com

  3. Available in print or e-book programming-elm.com

  4. None
  5. { ? }

  6. { dog: null, }

  7. FETCH?

  8. { fetching: true, dog: null, }

  9. SUCCESS?

  10. { fetching: false, success: true, dog: { name: 'Tucker' },

    }
  11. ERRORS?

  12. { fetching: false, success: false, dog: null, error: true, errorMessage:

    'Ruh roh!', }
  13. { fetching: true, success: true, dog: { name: 'Tucker' },

    error: true, errorMessage: 'Uh oh!', } ¯\_(ツ)_/¯ Invalid State
  14. { fetching: true, success: true, dog: { name: 'Tucker' },

    error: true, errorMessage: 'Uh oh!', } ¯\_(ツ)_/¯ Invalid State
  15. if (props.error) { ... } else if (props.fetching) { ...

    } else if (props.success) { ... } else { ... }
  16. STATE fetching success error ready

  17. PRIMITIVE OBSESSION USING COMIC SANS IS KINDA LIKE PRIMITIVE OBSESSION

  18. The Problem with Booleans…

  19. – Robert Harper “There is no information carried by a

    Boolean beyond its value, and that’s the rub.”
  20. binary data type with no inherent meaning boolean

  21. bookFlight('ATL', true) ?

  22. bookFlight('ATL', true) ? Offloading abstraction to our memory instead of

    the code.
  23. bookFlight('ATL', true, false, true) ? ? ?

  24. ?

  25. Boolean Algebra George Boole x ∧ y x ∨ y

    x ∨ (y ∧ z) ¬x
  26. Boolean Values true && true true || false true ||

    (true && false) !true
  27. Propositional Logic

  28. Premise 1: If it’s raining then it’s cloudy. Premise 2:

    It’s raining. Conclusion: It’s cloudy. Propositional Logic
  29. Premise 1: If it’s raining then it’s cloudy. Premise 2:

    It’s raining. Conclusion: It’s cloudy. PROPOSITIONS
  30. prop·o·si·tion a statement that expresses a concept that can be

    true or false
  31. Boolean ≠ Proposition A proposition, p, that is true is

    not the same as saying p is equal to true.
  32. LOSS OF INTENT

  33. LOSS OF INFORMATION

  34. 4

  35. bookFlight('ATL', true) ?

  36. function bookFlight(airport, isPremium) { if (isPremium) { ... } else

    { ... } }
  37. function bookFlight(airport, isPremium) { if (isPremium) { ... } else

    { ... } }
  38. function bookFlight(airport, isPremium) { if (isPremium) { ... } else

    { ... } } Regular customer?
  39. const OpacitySlider = createSlider(true) const VolumeSlider = createSlider(false) const App

    = () => ( <div> <OpacitySlider /> <VolumeSlider /> </div> ) ?
  40. const createSlider = isHorizontal => () => { if (isHorizontal)

    { ... } else { ... } }
  41. const createSlider = isHorizontal => () => { if (isHorizontal)

    { ... } else { ... } } Implicit vertical slider
  42. – Robert Martin “Boolean arguments loudly declare that the function

    does more than one thing. They are confusing and should be eliminated.”
  43. rotateFuelRod(fuelRod, 30, true) rotateControlRod( ) ?

  44. rotateFuelRod(fuelRod, 30, true) rotateControlRod(controlRod, 30, true)

  45. None
  46. function rotateFuelRod(fuelRod, amount, inDegrees) { ... } function rotateControlRod(controlRod, amount,

    inRadians) { ... }
  47. function rotateFuelRod(fuelRod, amount, inDegrees) { ... } function rotateControlRod(controlRod, amount,

    inRadians) { ... }
  48. function rotateFuelRod(fuelRod, amount, inDegrees) { ... } function rotateControlRod(controlRod, amount,

    inRadians) { ... }
  49. bookFlight('ATL', true, false, true) ? ? ?

  50. function bookFlight(airport, isPremium, hasCheckedLuggage, preferWindow) { const luggageCost = hasCheckedLuggage

    ? ... : ... if (isPremium) { if (hasCheckedLuggage) { ... } else { ... } } else if (hasCheckedLuggage) { ... } else { ... } }
  51. None
  52. – Martin Fowler “…an API should be written to make

    it easier for the caller, so if we know where the caller is coming from we should design the API with that information in mind.”
  53. Write code for humans Not computers

  54. None
  55. bookFlight('ATL', 'Premium')

  56. function bookFlight(airport, customerType) { switch (customerType) { case 'Premium': ...

    case 'Regular': ... default: ... } }
  57. function bookFlight(airport, customerType) { switch (customerType) { case 'Premium': ...

    case 'Regular': ... default: ... } }
  58. bookFlight('ATL', 'premium') bookFlight('ATL', 'economical') bookFlight('ATL', '') Primitive Obsession Revisited

  59. Represent a finite domain

  60. type CustomerType = Premium | Regular

  61. const CustomerType = { Premium: 'Premium', Regular: 'Regular', } bookFlight('ATL',

    CustomerType.Premium) bookFlight('ATL', CustomerType.Regular)
  62. function bookFlight(airport, customerType) { switch (customerType) { case CustomerType.Premium: ...

    case CustomerType.Regular: ... default: ... } }
  63. function bookFlight(airport, customerType) { switch (customerType) { case CustomerType.Premium: ...

    case CustomerType.Regular: ... default: ... } }
  64. enum CustomerType { Premium = 'Premium', Regular = 'Regular', }

    bookFlight('ATL', CustomerType.Premium) bookFlight('ATL', CustomerType.Regular)
  65. function bookFlight( airport: string, customerType: CustomerType, ): Promise<Flight> { switch

    (customerType) { case CustomerType.Premium: ... case CustomerType.Regular: ... } }
  66. function bookFlight( airport: string, customerType: CustomerType, ): Promise<Flight> { switch

    (customerType) { case CustomerType.Premium: ... case CustomerType.Regular: ... } }
  67. function bookFlight( airport: string, customerType: CustomerType, ): Promise<Flight> { switch

    (customerType) { case CustomerType.Premium: ... case CustomerType.Regular: ... } }
  68. const AngleType = { Degrees: 'Degrees', Radians: 'Radians', } const

    degrees = value => ({ kind: AngleType.Degrees, value }) const radians = value => ({ kind: AngleType.Radians, value }) rotateFuelRod(fuelRod, degrees(30)) rotateControlRod(controlRod, radians(Math.PI))
  69. const AngleType = { Degrees: 'Degrees', Radians: 'Radians', } const

    degrees = value => ({ kind: AngleType.Degrees, value }) const radians = value => ({ kind: AngleType.Radians, value }) rotateFuelRod(fuelRod, degrees(30)) rotateControlRod(controlRod, radians(Math.PI))
  70. const AngleType = { Degrees: 'Degrees', Radians: 'Radians', } const

    degrees = value => ({ kind: AngleType.Degrees, value }) const radians = value => ({ kind: AngleType.Radians, value }) rotateFuelRod(fuelRod, degrees(30)) rotateControlRod(controlRod, radians(Math.PI))
  71. const AngleType = { Degrees: 'Degrees', Radians: 'Radians', } const

    degrees = value => ({ kind: AngleType.Degrees, value }) const radians = value => ({ kind: AngleType.Radians, value }) rotateFuelRod(fuelRod, degrees(30)) rotateControlRod(controlRod, radians(Math.PI))
  72. enum AngleType { Degrees = 'Degrees', Radians = 'Radians', }

    type Angle = { kind: AngleType, value: number, }
  73. enum AngleType { Degrees = 'Degrees', Radians = 'Radians', }

    type Angle = { kind: AngleType, value: number, }
  74. enum AngleType { Degrees = 'Degrees', Radians = 'Radians', }

    type Angle = { kind: AngleType, value: number, }
  75. function rotateFuelRod( fuelRod: FuelRod, angle: Angle, ): FuelRod { switch

    (angle.kind) { case AngleType.Degrees: ... case AngleType.Radians: ... } }
  76. function rotate( rod: Rod, angle: Angle, ): Rod { switch

    (angle.kind) { case AngleType.Degrees: ... case AngleType.Radians: ... } }
  77. function rotate( rod: Rod, angle: Angle, ): Rod { switch

    (angle.kind) { case AngleType.Degrees: ... case AngleType.Radians: ... } }
  78. function rotate( rod: Rod, angle: Angle, ): Rod { switch

    (angle.kind) { case AngleType.Degrees: ... case AngleType.Radians: ... } }
  79. rotateInDegrees(fuelRod, 30) rotateInRadians(controlRod, Math.PI)

  80. rotateInDegrees(fuelRod, 30) rotateInRadians(controlRod, Math.PI) Still encourages primitive obsession

  81. function rotate( rod: Rod, angle: Angle, ): Rod { switch

    (angle.kind) { case AngleType.Degrees: return rotateInDegrees(rod, angle.value) case AngleType.Radians: return rotateInRadians(rod, angle.value) } }
  82. matchingStrings( Case.Insensitive, 'foo', ['FOOBAR', 'foobar'], ) matchingStrings( Case.Sensitive, 'foo', ['FOOBAR',

    'foobar'], )
  83. const matchingStrings = (case_, pattern, strings) => strings.filter(string => {

    switch (case_) { case Case.CaseSensitive: return string.includes(pattern) case Case.CaseInsensitive: return string .toUpperCase() .includes(pattern.toUpperCase()) } })
  84. const matchingStrings = (case_, pattern, strings) => strings.filter(string => {

    switch (case_) { case Case.CaseSensitive: return string.includes(pattern) case Case.CaseInsensitive: return string .toUpperCase() .includes(pattern.toUpperCase()) } })
  85. const matchingStrings = (case_, pattern, strings) => strings.filter(string => {

    switch (case_) { case Case.CaseSensitive: return string.includes(pattern) case Case.CaseInsensitive: return string .toUpperCase() .includes(pattern.toUpperCase()) } })
  86. const caseInsensitive = string => string.toUpperCase() const caseSensitive = string

    => string matchingStrings( caseInsensitive, 'foo', ['FOOBAR', 'foobar'], ) matchingStrings( caseSensitive, 'foo', ['FOOBAR', 'foobar'], )
  87. const caseInsensitive = string => string.toUpperCase() const caseSensitive = string

    => string matchingStrings( caseInsensitive, 'foo', ['FOOBAR', 'foobar'], ) matchingStrings( caseSensitive, 'foo', ['FOOBAR', 'foobar'], )
  88. const caseInsensitive = string => string.toUpperCase() const caseSensitive = string

    => string matchingStrings( caseInsensitive, 'foo', ['FOOBAR', 'foobar'], ) matchingStrings( caseSensitive, 'foo', ['FOOBAR', 'foobar'], )
  89. const matchingStrings = ( normalize, pattern, strings ) => strings.filter(string

    => normalize(string).includes(normalize(pattern)) )
  90. const matchingStrings = ( normalize, pattern, strings ) => strings.filter(string

    => normalize(string).includes(normalize(pattern)) )
  91. const matchingStrings = ( normalize, pattern, strings ) => strings.filter(string

    => normalize(string).includes(normalize(pattern)) )
  92. const bookPremiumCustomer = () => { ... } const bookRegularCustomer

    = () => { ... } bookFlight('ATL', bookPremiumCustomer) bookFlight('ATL', bookRegularCustomer)
  93. Make APIs UNDERSTANDABLE and CONVENIENT

  94. Function True False

  95. None
  96. function getTime(person) { if (doYouKnowTheTime(person)) { return tellMeTheTime(person) } else

    { return ` Does anybody really know what time it is? ` } }
  97. function getTime(person) { if (doYouKnowTheTime(person)) { return tellMeTheTime(person) } else

    { return ` Does anybody really know what time it is? ` } }
  98. function getTime(person) { if (doYouKnowTheTime(person)) { return tellMeTheTime(person) } else

    { return ` Does anybody really know what time it is? ` } }
  99. function getTime(person) { if (doYouKnowTheTime(person)) { return tellMeTheTime(person) } else

    { return ` Does anybody really know what time it is? ` } }
  100. function getTime(person) { if (doYouKnowTheTime(person)) { return tellMeTheTime(person) } else

    { return tellMeTheTime(person) } }
  101. Boolean Blindness

  102. – Conor McBride “To make use of a Boolean you

    have to know its provenance so that you can know what it means.”
  103. Get your organic, homegrown booleans from Rhode Island! Providence, RI

  104. PROVENANCE

  105. function findDogByName(name, dogs) { if (name in dogs) { return

    `${name} is a ${dogs[name].breed}`; } else { return 'Heck! No pupper found.'; } }
  106. function canDivide(denominator) { return denominator != 0 } function divisionResult(numerator,

    denominator) { if (canDivide(denominator)) { return `The result is ${numerator / denominator}` } else { return 'Could not divide' } }
  107. function canDivide(denominator) { return denominator != 0 } function divisionResult(numerator,

    denominator) { if (canDivide(denominator)) { return `The result is ${numerator / denominator}` } else { return 'Could not divide' } }
  108. function divisionResult(numerator, denominator) { if (canDivide(denominator)) { return `The result

    is ${numerator / denominator}` } else { return `The result is ${numerator / denominator}` } }
  109. – Dan Licata “Boolean tests let you look, options let

    you see.”
  110. Alternative Return Values

  111. type Maybe a = Nothing | Just a

  112. type Maybe a = Nothing | Just a

  113. type Maybe a = Nothing | Just a

  114. type Maybe a = Nothing | Just a

  115. 42 Just 42 "Hi" Just "Hi"

  116. Just 42 [42] Nothing [ ]

  117. import { Maybe } from 'true-myth' Maybe.just(42) // Just 42

    Maybe.nothing() // Nothing Maybe.of(42) // Just 42 Maybe.of(null) // Nothing Maybe.of(undefined) // Nothing
  118. function findDogByName(name, dogs) { return Maybe.of(dogs[name]) .map(dog => `${name} is

    a ${dog.breed}.`) .unwrapOr('Heck! No pupper found!') }
  119. function findDogByName(name, dogs) { return Maybe.of(dogs[name]) .map(dog => `${name} is

    a ${dog.breed}.`) .unwrapOr('Heck! No pupper found!') }
  120. function findDogByName(name, dogs) { return Maybe.of(dogs[name]) .map(dog => `${name} is

    a ${dog.breed}.`) .unwrapOr('Heck! No pupper found!') }
  121. function findDogByName(name, dogs) { return Maybe.of(dogs[name]) .map(dog => `${name} is

    a ${dog.breed}.`) .unwrapOr('Heck! No pupper found!') }
  122. whatTimeIsIt(person) .map(time => ...) .unwrapOr(...)

  123. import { Result } from 'true-myth' Result.ok(42) // Ok 42

    Result.err('Uh oh') // Err 'Uh oh'
  124. const divide = (numerator, denominator) => denominator === 0 ?

    Result.err('Divide by zero') : Result.ok(numerator / denominator) const divisionResult = (numerator, denominator) => divide(numerator, denominator) .mapOrElse( error => `Could not divide: ${error}`, result => `The result is ${result}`, )
  125. const divide = (numerator, denominator) => denominator === 0 ?

    Result.err('Divide by zero') : Result.ok(numerator / denominator) const divisionResult = (numerator, denominator) => divide(numerator, denominator) .mapOrElse( error => `Could not divide: ${error}`, result => `The result is ${result}`, )
  126. const divide = (numerator, denominator) => denominator === 0 ?

    Result.err('Divide by zero') : Result.ok(numerator / denominator) const divisionResult = (numerator, denominator) => divide(numerator, denominator) .mapOrElse( error => `Could not divide: ${error}`, result => `The result is ${result}`, )
  127. See with Special Types

  128. Back to State { fetching: false, success: true, dog: {

    name: "Tucker" }, error: False, errorMessage: "", }
  129. if (props.error) { ... } else if (props.fetching) { ...

    } else if (props.success) { ... } else { ... }
  130. { fetching: true, success: true, dog: { name: "Tucker" },

    error: true, errorMessage: "Uh oh!", }
  131. https://youtu.be/IcgmSRJHu_8

  132. STATE fetching success error ready

  133. const RemoteDoggo = { Ready: 'Ready', Fetching: 'Fetching', Success: 'Success',

    Fail: 'Fail', }
  134. const ready = () => ({ status: RemoteDoggo.Ready }) const

    fetching = () => ({ status: RemoteDoggo.Fetching }) const success = value => ({ status: RemoteDoggo.Success, value }) const fail = message => ({ status: RemoteDoggo.Fail, message })
  135. const ready = () => ({ status: RemoteDoggo.Ready }) const

    fetching = () => ({ status: RemoteDoggo.Fetching }) const success = value => ({ status: RemoteDoggo.Success, value }) const fail = message => ({ status: RemoteDoggo.Fail, message })
  136. { dog: ready(), ... } { dog: fetching(), ... }

    { dog: success({ name: 'Tucker' }), ... } { dog: fail('Uh oh!'), ... }
  137. function App({ dog }) { switch (dog.status) { case RemoteDoggo.Ready:

    return <FindDog /> case RemoteDoggo.Fetching: return <Spinner /> case RemoteDoggo.Success: return <Dog dog={dog.value} /> case RemoteDoggo.Fail: return <Error message={dog.message} /> } }
  138. function App({ dog }) { switch (dog.status) { case RemoteDoggo.Ready:

    return <FindDog /> case RemoteDoggo.Fetching: return <Spinner /> case RemoteDoggo.Success: return <Dog dog={dog.value} /> case RemoteDoggo.Fail: return <Error message={dog.message} /> } }
  139. enum Status { Ready = 'Ready', Fetching = 'Fetching', Success

    = 'Success', Fail = 'Fail', } type RemoteDoggo = { kind: Status.Ready } | { kind: Status.Fetching } | { kind: Status.Success, value: Dog } | { kind: Status.Fail, message: string }
  140. function App({ dog }: AppProps): React.ReactElement { switch (dog.kind) {

    case Status.Ready: return <FindDog /> case Status.Fetching: return <Spinner /> case Status.Success: return <Dog dog={dog.value} /> // case Status.Fail: // return <Error message={dog.message} /> } }
  141. app.tsx:20:34 - error TS2366: Function lacks ending return statement and

    return type does not include 'undefined'. 20 function App({ dog }: AppProps): React.ReactElement { ~~~~~~~~~~~~~~~~~~ Found 1 error.
  142. Impossible state becomes impossible* Code becomes understandable *trademark Richard Feldman

  143. But wait, There’s MORE! AS SEEN ON U I

  144. Save to archive

  145. Save to archive A wild checkbox appears!

  146. Save to archive ✓

  147. Save to archive ?

  148. None
  149. We design APIs for callers So we should design UIs

    for users
  150. None
  151. hu·mane having or showing compassion or benevolence

  152. Save to archive ?

  153. Save to archive Save to inbox

  154. Save to archive Save to inbox

  155. Save to archive Save to inbox Verb labels = when

    will it happen?
  156. Saved to archive Saved to inbox Adjective labels = describe

    the final result.
  157. Goodbye, boolean?

  158. B A L A N C E

  159. EMPATHY

  160. Jeremy Fairbank @elpapapollo Slides: bit.ly/ct-bool