Types and Immutability: why you should care

Jean Carlo Emer
Jean Carlo EmerSenior Developer at Work & Co
why you should care
@jcemer
Types and
Immutability
@jcemer

jcemer.com
Types and Immutability: why you should care
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
JavaScript is a high-
level, dynamic, weakly
typed, object-based, 

multi-paradigm, and

interpreted language 
According Wikipedia
01Data
Types
A type is a set of
similar values
with associated
operations
4
2.1
893
12
2.3
5.3 *
56
1
3
4
6
9.4
ObjectString
Number
Undefined
Null
Boolean
Symbol
Literal
Array
Function
Date
JSON
…
Primitives
undefined?
Types in
JavaScript have
always been a
headache
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
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™
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)
}
}
Modern

errors
The new
keyword is
missing
Common Mistake #1:

Incorrect references
to this
The 10 Most Common Mistakes
JavaScript Developers Make 

by Ryan J. Peterson
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")
Types and Immutability: why you should care
1 * 'foo'
'foo' * 1
'foo' + 1
[] + {}
({}) + {}
null + 1
5 % undefined
null.prop
undefined()
1. NaN
2. undefined is not a function
3. incorrect this reference
4. cannot read/set any
property of undefined/null
5. silent errors
Those are all typical
examples of runtime
errors from a
dynamic language
02Type
Checking
flow.org
Static type checking
is performed before
running code
eslint.org
Let’s add types to
help programmers
and not computers
Product
Name
Cost
Tax
Price()
String
Number
Number
Number
/* @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!
Types and Immutability: why you should care
typescript

lang.org
Types and Immutability: why you should care
primitives

objects (arrays, classes, …)

literal
+
Types
any


nullable or maybe


union and intersection
+
Advanced Types
Any value
null or Product
Product or FreeProduct
new types (aliases)


interfaces


generics
+
Fancy Types
Cost is a number
Any value with price method
“a way of abstracting a type away”
Type Signature
allows you to
foresee problems
Types as Design Tools 

by Kris Jenkins
/* @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!
A Type System is,
first and foremost, 

a communication
mechanism
Tweet by Sarah Mei
A Type System replaces
direct communication
with other humans, when
such communication isn't
practical - large teams,
open source, etc
Tweet by Sarah Mei
Types and Immutability: why you should care
03IO Data
Parsing
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
interface ItemsResponse {
results: string[]
}
{
"results": [
"Item 1",
"Item 2",
]
}
Code
API Responses
{
"results": [
8,
4,
]
}
Oops!
Trust me, 

I'm an 

engineer
/* @flow */
const someValue: any = null
const strLength: number = someValue.length
any is a 

bad guy!
Using any is
completely unsafe,
and should be avoided
whenever possible
from Flow documentation
Runtime exception:
the case of broken
data not being
handled
elm-lang.org
Elm is a statically
typed language
with no runtime
exceptions
type alias Product =
{ name : String
, cost : Float
, tax : Float
}
price : Product -> Float
price {cost,tax} =
cost * (tax + 1)
Almost only
type annotation
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)
Types and Immutability: why you should care
> 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)
Request
Response
Ok
Render results
Show an error 

message
Err
A Result wraps any
computation that may
fail, this is a great way
to manage errors
Elm documentation
There is no
exception in Elm,
the code must cover
all edge cases
Relax, you don’t
need to move away
from JavaScript!
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
+
github.com/
gcanti/

babel-plugin-
tcomb
bit.ly/

runtime-type-
validation
+
We should focus our
efforts on either avoiding
—or fixing!—the corner
case value coercions
Fixing Coercion, Not
The Symptoms by Kyle Simpson
04Immuta
bility
All JavaScript
primitives are
immutable
Types and Immutability: why you should care
But JavaScript
objects are
mutable
Oops!
Side effects
User
Product
Data model UI components
user.father.name = "Peter"
X
X
X
X
X
X
X
X
Father Mother …
…
…
A small change on
mutable data implies
on check and render
all descendants
components
No way to
watch 

changes!
🙏
Immutability
is a very good
paradigm
Immutable data
just is, once
created, it will be
the same forever
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
UI components
Re-render
user === newUser 

// false
product === newProduct 

// true
No re-render
Immutable 

data removes
complexity
Immutable Data and React 

by Lee Byron
Immutability improve
performance when used
with React Pure
Component or Angular
OnPush Change Detection
redux.js.org



github.com/

jcemer/
minimalistic-
shop
Oops
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, …]
// 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!
Array manipulation
is very optimized
when performed
with mutation
05
Persistent
data
structures
facebook.

github.io/
immutable-js/
Think about
managing the data
like code on Git
Immutable data structures for
functional JS by Anjana Vakil
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)
Types and Immutability: why you should care
Hash Array
Mapped Trie
Immutable Data
and React
Immutable data
structures for
functional JS
youtu.be/Wo0qiGPSV-s
youtu.be/I7IdS-PbEgI
const user = {
name: "Paul",
father: { name: "John" },
mother: { name: "Ana" }
}
const item = Immutable.fromJS(user)
const newItem = item.setIn(

["father", "name"], "Peter"

)
Deep change
ImmutableJS has poor
docs, hard debugging
and enforces a new API
for data manipulation
redux.js.org/
docs/

recipes/
UsingImmutableJ
S.html
06Immutable
languages
All values in Elm
are immutable
According Wikipedia 🤔
There are many tools
and languages
nowadays that enforce
Pure Functional
Paradigm
staltz.com/

is-your-javascript-
function-actually-
pure.html
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
Types and Immutability: why you should care
***
I hope you learned
something new!
@jcemer
Thank you
Special
thanks
Hugo Bessa
Rafael Rinaldi
Rodrigo Willrich
Zeh Fernandes
Marcelo Boeira
Felipe Fialho
Rachel Mason
1 of 99

More Related Content

What's hot

Solid principlesSolid principles
Solid principlesHanokh Aloni
578 views39 slides
Prototype FrameworkPrototype Framework
Prototype FrameworkJulie Iskander
1.4K views50 slides
jQueryjQuery
jQueryJon Erickson
1.7K views20 slides

What's hot(20)

Solid principlesSolid principles
Solid principles
Hanokh Aloni578 views
Prototype FrameworkPrototype Framework
Prototype Framework
Julie Iskander1.4K views
jQueryjQuery
jQuery
Jon Erickson1.7K views
Scala best practicesScala best practices
Scala best practices
Alexander Zaidel319 views
Approaching (almost) Any NLP ProblemApproaching (almost) Any NLP Problem
Approaching (almost) Any NLP Problem
Abhishek Thakur9.3K views
Clean Code DevelopmentClean Code Development
Clean Code Development
Peter Gfader2.6K views
ddd+scaladdd+scala
ddd+scala
潤一 加藤3.1K views
Grammarware MemesGrammarware Memes
Grammarware Memes
Eelco Visser840 views
JavaTalks: OOD principlesJavaTalks: OOD principles
JavaTalks: OOD principles
stanislav bashkirtsev1.3K views
core.logic introductioncore.logic introduction
core.logic introduction
Norman Richards4.4K views
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander861 views
03. haskell refresher quiz03. haskell refresher quiz
03. haskell refresher quiz
Sebastian Rettig1K views
Python review2Python review2
Python review2
vibrantuser39 views
Functional DDDFunctional DDD
Functional DDD
Alessandro Melchiori3.1K views
Swift for TensorFlow - CoreML PersonalizationSwift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML Personalization
Jacopo Mangiavacchi176 views
JavaScript Foundations Day1JavaScript Foundations Day1
JavaScript Foundations Day1
Troy Miles677 views
Lodash jsLodash js
Lodash js
LearningTech1.8K views
Scala vs java 8Scala vs java 8
Scala vs java 8
François Sarradin2.7K views

Similar to Types and Immutability: why you should care(20)

Python: The Dynamic!Python: The Dynamic!
Python: The Dynamic!
Omid Mogharian729 views
ArraysArrays
Arrays
Komal Singh1.5K views
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in Swift
Michele Titolo9.1K views
Oct27Oct27
Oct27
Tak Lee419 views
Intro to PythonIntro to Python
Intro to Python
OSU Open Source Lab1.4K views
JavaJava
Java
Ashen Disanayaka1.2K views
Meet scalaMeet scala
Meet scala
Wojciech Pituła317 views
Java script objects 1Java script objects 1
Java script objects 1
H K1.2K views
Software fundamentalsSoftware fundamentals
Software fundamentals
Susan Winters432 views
Extreme SwiftExtreme Swift
Extreme Swift
Movel1K views
Types in JavaScript: why you should careTypes in JavaScript: why you should care
Types in JavaScript: why you should care
Jean Carlo Emer536 views
Computation Chapter 4Computation Chapter 4
Computation Chapter 4
Inocentshuja Ahmad209 views

Types and Immutability: why you should care