Slide 1

Slide 1 text

Jeremy Fairbank @elpapapollo bit.ly/cm-bool

Slide 2

Slide 2 text

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

Slide 3

Slide 3 text

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

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

{ ? }

Slide 6

Slide 6 text

{ dog: null, }

Slide 7

Slide 7 text

FETCH?

Slide 8

Slide 8 text

{ fetching: true, dog: null, }

Slide 9

Slide 9 text

SUCCESS?

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

ERRORS?

Slide 12

Slide 12 text

{ fetching: false, success: false, dog: null, error: true, errorMessage: 'Ruh roh!', }

Slide 13

Slide 13 text

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

Slide 14

Slide 14 text

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

Slide 15

Slide 15 text

if (props.error) { ... } else if (props.fetching) { ... } else if (props.success) { ... } else { ... }

Slide 16

Slide 16 text

STATE fetching success error ready

Slide 17

Slide 17 text

PRIMITIVE OBSESSION USING COMIC SANS IS KINDA LIKE PRIMITIVE OBSESSION

Slide 18

Slide 18 text

The Problem with Booleans…

Slide 19

Slide 19 text

– Robert Harper “There is no information carried by a Boolean beyond its value, and that’s the rub.”

Slide 20

Slide 20 text

binary data type with no inherent meaning boolean

Slide 21

Slide 21 text

bookFlight('CLE', true) ?

Slide 22

Slide 22 text

bookFlight('CLE', true) ? Offloading abstraction to our memory instead of the code.

Slide 23

Slide 23 text

bookFlight('CLE', true, false, true) ? ? ?

Slide 24

Slide 24 text

?

Slide 25

Slide 25 text

Boolean Algebra George Boole x ∧ y x ∨ y x ∨ (y ∧ z) ¬x

Slide 26

Slide 26 text

Boolean Values true && true true || false true || (true && false) !true

Slide 27

Slide 27 text

Propositional Logic

Slide 28

Slide 28 text

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

Slide 29

Slide 29 text

Premise 1: If it’s raining then it’s cloudy. Premise 2: It’s raining. Conclusion: It’s cloudy. PROPOSITIONS

Slide 30

Slide 30 text

prop·o·si·tion a statement that expresses a concept that can be true or false

Slide 31

Slide 31 text

Boolean ≠ Proposition A proposition, p, that is true is not the same as saying p is equal to true.

Slide 32

Slide 32 text

LOSS OF INTENT

Slide 33

Slide 33 text

LOSS OF INFORMATION

Slide 34

Slide 34 text

4

Slide 35

Slide 35 text

bookFlight('CLE', true) ?

Slide 36

Slide 36 text

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

Slide 37

Slide 37 text

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

Slide 38

Slide 38 text

function bookFlight(airport, isPremium) { if (isPremium) { ... } else { ... } } Regular customer?

Slide 39

Slide 39 text

const OpacitySlider = createSlider(true) const VolumeSlider = createSlider(false) const App = () => (
) ?

Slide 40

Slide 40 text

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

Slide 41

Slide 41 text

const createSlider = isHorizontal => () => { if (isHorizontal) { ... } else { ... } } Implicit vertical slider

Slide 42

Slide 42 text

– Robert Martin “Boolean arguments loudly declare that the function does more than one thing. They are confusing and should be eliminated.”

Slide 43

Slide 43 text

rotateFuelRod(fuelRod, 30, true) rotateControlRod( ) ?

Slide 44

Slide 44 text

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

Slide 45

Slide 45 text

No content

Slide 46

Slide 46 text

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

Slide 47

Slide 47 text

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

Slide 48

Slide 48 text

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

Slide 49

Slide 49 text

bookFlight('CLE', true, false, true) ? ? ?

Slide 50

Slide 50 text

function bookFlight(airport, isPremium, hasCheckedLuggage, preferWindow) { const luggageCost = hasCheckedLuggage ? ... : ... if (isPremium) { if (hasCheckedLuggage) { ... } else { ... } } else if (hasCheckedLuggage) { ... } else { ... } }

Slide 51

Slide 51 text

No content

Slide 52

Slide 52 text

– 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.”

Slide 53

Slide 53 text

Write code for humans Not computers

Slide 54

Slide 54 text

No content

Slide 55

Slide 55 text

bookFlight('CLE', 'Premium')

Slide 56

Slide 56 text

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

Slide 57

Slide 57 text

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

Slide 58

Slide 58 text

bookFlight('CLE', 'premium') bookFlight('CLE', 'economical') bookFlight('CLE', '') Primitive Obsession Revisited

Slide 59

Slide 59 text

Represent a finite domain

Slide 60

Slide 60 text

type CustomerType = Premium | Regular

Slide 61

Slide 61 text

bookFlight "CLE" Premium bookFlight "CLE" Regular

Slide 62

Slide 62 text

bookFlight city customerType = case customerType of Premium -> ... Regular -> ...

Slide 63

Slide 63 text

bookFlight city customerType = case customerType of Premium -> ... Regular -> ...

Slide 64

Slide 64 text

bookFlight city customerType = case customerType of Premium -> ... Regular -> ...

Slide 65

Slide 65 text

const CustomerType = { Premium: 'Premium', Regular: 'Regular', } bookFlight('CLE', CustomerType.Premium) bookFlight('CLE', CustomerType.Regular)

Slide 66

Slide 66 text

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

Slide 67

Slide 67 text

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

Slide 68

Slide 68 text

enum CustomerType { Premium = 'Premium', Regular = 'Regular', } bookFlight('CLE', CustomerType.Premium) bookFlight('CLE', CustomerType.Regular)

Slide 69

Slide 69 text

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

Slide 70

Slide 70 text

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

Slide 71

Slide 71 text

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

Slide 72

Slide 72 text

const AngleType = { Degrees: 'Degrees', Radians: 'Radians', } const degrees = value => ({ kind: AngleType.Degrees, value }) const radians = value => ({ kind: AngleType.Radians, value })

Slide 73

Slide 73 text

const AngleType = { Degrees: 'Degrees', Radians: 'Radians', } const degrees = value => ({ kind: AngleType.Degrees, value }) const radians = value => ({ kind: AngleType.Radians, value })

Slide 74

Slide 74 text

const AngleType = { Degrees: 'Degrees', Radians: 'Radians', } const degrees = value => ({ kind: AngleType.Degrees, value }) const radians = value => ({ kind: AngleType.Radians, value })

Slide 75

Slide 75 text

rotateFuelRod(fuelRod, degrees(30)) rotateControlRod(controlRod, radians(Math.PI))

Slide 76

Slide 76 text

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

Slide 77

Slide 77 text

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

Slide 78

Slide 78 text

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

Slide 79

Slide 79 text

function rotateFuelRod( fuelRod: FuelRod, angle: Angle, ): FuelRod { switch (angle.kind) { case AngleType.Degrees: ... case AngleType.Radians: ... } }

Slide 80

Slide 80 text

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

Slide 81

Slide 81 text

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

Slide 82

Slide 82 text

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

Slide 83

Slide 83 text

rotateInDegrees(fuelRod, 30) rotateInRadians(controlRod, Math.PI)

Slide 84

Slide 84 text

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

Slide 85

Slide 85 text

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) } }

Slide 86

Slide 86 text

matchingStrings( Case.Insensitive, 'foo', ['FOOBAR', 'foobar'], ) matchingStrings( Case.Sensitive, 'foo', ['FOOBAR', 'foobar'], )

Slide 87

Slide 87 text

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()) } })

Slide 88

Slide 88 text

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()) } })

Slide 89

Slide 89 text

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()) } })

Slide 90

Slide 90 text

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

Slide 91

Slide 91 text

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

Slide 92

Slide 92 text

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

Slide 93

Slide 93 text

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

Slide 94

Slide 94 text

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

Slide 95

Slide 95 text

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

Slide 96

Slide 96 text

const matchingStrings = ( normalize, pattern, strings ) => strings.filter(string => normalize(string).includes(normalize(pattern)) ) Higher-order Function

Slide 97

Slide 97 text

const bookPremiumCustomer = () => { ... } const bookRegularCustomer = () => { ... } bookFlight('CLE', bookPremiumCustomer) bookFlight('CLE', bookRegularCustomer)

Slide 98

Slide 98 text

Make APIs UNDERSTANDABLE and CONVENIENT

Slide 99

Slide 99 text

Function True False

Slide 100

Slide 100 text

No content

Slide 101

Slide 101 text

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

Slide 102

Slide 102 text

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

Slide 103

Slide 103 text

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

Slide 104

Slide 104 text

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

Slide 105

Slide 105 text

function getTime(person) { if (doYouKnowTheTime(person)) { return tellMeTheTime(person) } else { return tellMeTheTime(person) } }

Slide 106

Slide 106 text

Boolean Blindness

Slide 107

Slide 107 text

– Conor McBride “To make use of a Boolean you have to know its provenance so that you can know what it means.”

Slide 108

Slide 108 text

Get your organic, homegrown booleans from Rhode Island! Providence, RI

Slide 109

Slide 109 text

PROVENANCE

Slide 110

Slide 110 text

function findDogByName(name, dogs) { if (name in dogs) { return `${name} is a ${dogs[name].breed}`; } else { return 'Heck! No pupper found.'; } }

Slide 111

Slide 111 text

function findDogByName(name, dogs) { if (name in dogs) { return `${name} is a ${dogs[name].breed}`; } else { return `${name} is a ${dogs[name].breed}`; } }

Slide 112

Slide 112 text

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

Slide 113

Slide 113 text

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

Slide 114

Slide 114 text

function divisionResult(numerator, denominator) { if (canDivide(denominator)) { return `The result is ${numerator / denominator}` } else { return `The result is ${numerator / denominator}` } }

Slide 115

Slide 115 text

– Dan Licata “Boolean tests let you look, options let you see.”

Slide 116

Slide 116 text

Alternative Return Values

Slide 117

Slide 117 text

type Maybe a = Nothing | Just a

Slide 118

Slide 118 text

type Maybe a = Nothing | Just a

Slide 119

Slide 119 text

type Maybe a = Nothing | Just a

Slide 120

Slide 120 text

type Maybe a = Nothing | Just a

Slide 121

Slide 121 text

42 Just 42 "Hi" Just "Hi"

Slide 122

Slide 122 text

Just 42 [42] Nothing [ ]

Slide 123

Slide 123 text

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

Slide 124

Slide 124 text

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

Slide 125

Slide 125 text

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

Slide 126

Slide 126 text

Maybe.of undefined Maybe.of Nothing dog Just dog

Slide 127

Slide 127 text

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

Slide 128

Slide 128 text

.map n => n * 2 Just 21 .map n => n * 2 Just 42 Nothing Nothing

Slide 129

Slide 129 text

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

Slide 130

Slide 130 text

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

Slide 131

Slide 131 text

.unwrapOr(-1) Just 42 .unwrapOr(-1) 42 Nothing -1

Slide 132

Slide 132 text

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

Slide 133

Slide 133 text

whatTimeIsIt(person) .map(time => ...) .unwrapOr(...)

Slide 134

Slide 134 text

type Result error value = Ok value | Err error

Slide 135

Slide 135 text

type Result error value = Ok value | Err error

Slide 136

Slide 136 text

type Result error value = Ok value | Err error

Slide 137

Slide 137 text

import { Result } from 'true-myth' Result.ok(42) // Ok 42 Result.err('Uh oh') // Err 'Uh oh'

Slide 138

Slide 138 text

const divide = (numerator, denominator) => denominator === 0 ? Result.err('Divide by zero') : Result.ok(numerator / denominator)

Slide 139

Slide 139 text

const divide = (numerator, denominator) => denominator === 0 ? Result.err('Divide by zero') : Result.ok(numerator / denominator)

Slide 140

Slide 140 text

const divide = (numerator, denominator) => denominator === 0 ? Result.err('Divide by zero') : Result.ok(numerator / denominator)

Slide 141

Slide 141 text

const divide = (numerator, denominator) => denominator === 0 ? Result.err('Divide by zero') : Result.ok(numerator / denominator)

Slide 142

Slide 142 text

const divisionResult = (numerator, denominator) => divide(numerator, denominator) .mapOrElse( error => `Could not divide: ${error}`, quotient => `The quotient is ${quotient}`, )

Slide 143

Slide 143 text

const divisionResult = (numerator, denominator) => divide(numerator, denominator) .mapOrElse( error => `Could not divide: ${error}`, quotient => `The quotient is ${quotient}`, )

Slide 144

Slide 144 text

const divisionResult = (numerator, denominator) => divide(numerator, denominator) .mapOrElse( error => `Could not divide: ${error}`, quotient => `The quotient is ${quotient}`, )

Slide 145

Slide 145 text

const divisionResult = (numerator, denominator) => divide(numerator, denominator) .mapOrElse( error => `Could not divide: ${error}`, quotient => `The quotient is ${quotient}`, )

Slide 146

Slide 146 text

See with Special Types

Slide 147

Slide 147 text

Back to State { fetching: false, success: true, dog: { name: "Tucker" }, error: False, errorMessage: "", }

Slide 148

Slide 148 text

if (props.error) { ... } else if (props.fetching) { ... } else if (props.success) { ... } else { ... }

Slide 149

Slide 149 text

{ fetching: true, success: true, dog: { name: "Tucker" }, error: true, errorMessage: "Uh oh!", }

Slide 150

Slide 150 text

https://youtu.be/IcgmSRJHu_8

Slide 151

Slide 151 text

STATE fetching success error ready

Slide 152

Slide 152 text

const RemoteDoggo = { Ready: 'Ready', Fetching: 'Fetching', Success: 'Success', Fail: 'Fail', }

Slide 153

Slide 153 text

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

Slide 154

Slide 154 text

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

Slide 155

Slide 155 text

{ dog: ready(), ... } { dog: fetching(), ... } { dog: success({ name: 'Tucker' }), ... } { dog: fail('Uh oh!'), ... }

Slide 156

Slide 156 text

function App({ dog }) { switch (dog.status) { case RemoteDoggo.Ready: return case RemoteDoggo.Fetching: return case RemoteDoggo.Success: return case RemoteDoggo.Fail: return } }

Slide 157

Slide 157 text

function App({ dog }) { switch (dog.status) { case RemoteDoggo.Ready: return case RemoteDoggo.Fetching: return case RemoteDoggo.Success: return case RemoteDoggo.Fail: return } }

Slide 158

Slide 158 text

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 }

Slide 159

Slide 159 text

function App({ dog }: AppProps): React.ReactElement { switch (dog.kind) { case Status.Ready: return case Status.Fetching: return case Status.Success: return // case Status.Fail: // return } }

Slide 160

Slide 160 text

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.

Slide 161

Slide 161 text

Impossible state becomes impossible* Code becomes understandable *trademark Richard Feldman

Slide 162

Slide 162 text

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

Slide 163

Slide 163 text

Save to archive

Slide 164

Slide 164 text

Save to archive A wild checkbox appears!

Slide 165

Slide 165 text

Save to archive ✓

Slide 166

Slide 166 text

Save to archive ?

Slide 167

Slide 167 text

No content

Slide 168

Slide 168 text

We design APIs for callers So we should design UIs for users

Slide 169

Slide 169 text

No content

Slide 170

Slide 170 text

hu·mane having or showing compassion or benevolence

Slide 171

Slide 171 text

Save to archive ?

Slide 172

Slide 172 text

Save to archive Save to inbox

Slide 173

Slide 173 text

Save to archive Save to inbox

Slide 174

Slide 174 text

Save to archive Save to inbox Verb labels = when will it happen?

Slide 175

Slide 175 text

Saved to archive Saved to inbox Adjective labels = describe the final result.

Slide 176

Slide 176 text

Goodbye, boolean?

Slide 177

Slide 177 text

B A L A N C E

Slide 178

Slide 178 text

EMPATHY

Slide 179

Slide 179 text

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