SlideShare a Scribd company logo
1 of 55
Download to read offline
Func up your code
Maciej Komorowski
What is func%onal programming?
Func%onal programming is
programming paradigm [...] that
treats computa%on as the evalua%on
of mathema&cal func&ons and
avoids changing-state and mutable
data.
— Wikipedia
Pillars of FP
• Higher-order func0ons (e.g. map)
• Immutable data
• Lazy evalua0on
• Pure func0ons
• Recursion
Pure func)on
! Always evaluates the same result value given the same
arguments
! Does not cause any seman5cally observable side effect, such as
muta5on of mutable objects
Pure func)on examples
// Pure
function add(a, b) {
return a + b;
}
// Impure
Math.random();
// Impure
const items = []
function addItem(item) {
return items.push(item);
}
State muta(on
State muta(on in OOP
! Relies heavily on encapsula)on
! Has hidden nature
! Brings nondeterminism
! Root cause of doom
Brogrammer1
State muta)on example
A brogrammer is [...] a slang term for a
macho, male programmer. A brogrammer
might self-describe as a sociable
programmer.
— Wikipedia
1
Frans Hals, Oil on canvas, 1630. Source: classicprogrammerpain;ngs
What brogrammer does?
• drinkBeer
• talk
Stateful implementa*on
class Brogrammer {
constructor() {
this.beers = 0;
}
drinkBeer() { /* ... */ }
talk() { /* ... */ }
}
Stateful – drinkBeer
it('increment number of drunk beers', () => {
expect(brogrammer.drinkBeer()).toEqual(1);
expect(brogrammer.drinkBeer()).toEqual(2);
});
// Inside Brogrammer class
drinkBeer() {
return this.beers += 1; // encapsulates 'beers'
}
Stateful – talk tests
it('says "Beer me up!" before drinking', () => {
expect(brogrammer.talk()).toEqual("Beer me up!");
});
it('says "Yummy" after 1st beer', () => {
brogrammer.drinkBeer();
expect(brogrammer.talk()).toEqual("Yummy");
});
it('says "I a<M dRuNk" after 10th beer', () => {
brogrammer.drinkBeer();
// 8 x brogrammer.drinkBeer();
brogrammer.drinkBeer();
expect(brogrammer.talk()).toEqual("I a<M dRuNk");
});
Stateful – talk implementa+on
// Inside Brogrammer class
talk() {
return ({
0: 'Beer me up!',
1: 'Yummy',
// ...
10: 'I a<M dRuNk',
})[this.beers] || '';
}
How to remove state?
Single source of truth
Naïve stateless – implementa+on
class Brogrammer {
constructor(store) {
this.store = store;
}
// ...
}
Naïve stateless – drinkBeer tests
it('increment number of drunk beers', () => {
const store = { beers: 0 };
const brogrammer = new Brogrammer(store);
brogrammer.drinkBeer();
expect(store.beers).toEqual(1);
});
Naïve stateless – drinkBeer implementa+on
// Inside Brogrammer class
drinkBeer() {
return this.store.beers += 1;
}
Naïve stateless – talk tests
it('says "I a<M dRuNk" after 10th beer', () => {
const store = { beers: 10 };
const brogrammer = new Brogrammer(store);
expect(brogrammer.talk()).toEqual("I a<M dRuNk");
});
Naïve stateless – talk implementa+on
// Inside Brogrammer class
talk() {
return ({
0: 'Beer me up!',
1: 'Yummy',
// ...
10: 'I a<M dRuNk',
})[this.store.beers] || '';
}
Solu%on review
! Removed state from the Brogrammer
! Easier tes2ng
" Lost encapsula-on
How to improve?
The Redux way
Redux workflow2
2
Source: CSS-Tricks
Three Principles of Redux3
! Single source of truth
! State is read-only
! Changes are made with pure func)ons
3
Source: Redux
Three Principles of Redux
Single source of truth
console.log(store.getState());
// {
// brogrammer: {
// beers: 0
// }
// }
Three Principles of Redux
State is read-only
store.dispatch({
type: 'INCREMENT_BEERS',
});
Three Principles of Redux
Changes are made with pure func3ons
function brogrammer(state = {}, action) {
switch (action.type) {
case 'SET_BEERS':
return {
...state,
beers: 5,
};
// case ...
}
}
Redux – incrementBeers ac%on
it('returns action with type INCREMENT_BEERS', () => {
const action = incrementBeers();
expect(action).toEqual({
type: 'INCREMENT_BEERS'
});
});
Redux – incrementBeers ac%on
const incrementBeers = () => ({
type: 'INCREMENT_BEERS',
});
Redux – brogrammer reducer
it('returns state with incremented beers', () => {
const state = { beers: 0 };
const action = incrementBeers();
const nextState = brogrammer(state, action);
expect(nextState).toEqual({ beers: 1 });
});
Redux – brogrammer reducer
implementa)on
const brogrammer = (state = {}, action) => {
switch (action.type) {
case 'INCREMENT_BEERS':
return {
...state,
beers: state.beers + 1
};
default:
return state
}
}
Redux – drinkBeer tests
it('increment number of drunk beers', () => {
const store = createStore({ beers: 0 });
const brogrammer = new Brogrammer(store);
brogrammer.drinkBeer();
expect(store.dispatch)
.toHaveBeenCalledWith(incrementBeers());
});
Redux – drinkBeer implementa+on
// Inside Brogrammer class
drinkBeer() {
return this.store.dispatch(incrementBeers());
}
Redux – talk tests
it('says "I a<M dRuNk" after 10th beer', () => {
const store = createStore({ beers: 10 });
const brogrammer = new Brogrammer(store);
expect(brogrammer.talk()).toEqual("I a<M dRuNk");
});
Redux – talk implementa+on
// Inside Brogrammer class
talk() {
return ({
0: 'Beer me up!',
1: 'Yummy',
// ...
10: 'I a<M dRuNk',
})[this.store.get('beers')] || '';
}
Solu%on review
! Easy tes(ng
! Be,er separa(on
! Explicit state changes
! Full control over state
A few thoughts on Redux
Immutable data
Mutable vs immutable
// Mutable
const items = ['foo'];
items.push('bar');
items.push('baz');
console.log(items); // ["foo", "bar", "baz"]
Mutable vs immutable
// Immutable via immutable-js
const items = Immutable.List.of('foo');
items.push('bar');
items.push('baz');
console.log(items.toArray());
// ["foo"]
console.log(items.push('bar').push('baz').toArray());
// ["foo", "bar", "baz"]
What about performance?5
5
Source: React.js Conf 2015 - Immutable Data and React
Performance benchmark
Array push 1,000,000 items:
var list = [];
for (var i = 0; i < 1000000; i++) {
list.push(i);
}
83 ms
Performance benchmark
Mori immutable vector conj 1,000,000 items:
var list = mori.vector();
for (var i = 0; i < 1000000; i++) {
mori.conj(list, i);
}
288 ms
Should update problem
const form = { /* ... */ };
function submit(form) {
if (hasChanged(form)) {
doSomethingExpensive(form);
}
}
Should update problem
versioning
let currentFormVersion;
function hasChanged(form) {
const formVersion = md5(JSON.stringify(form));
return formVersion !== currentFormVersion;
}
Should update problem
dirty bits
function hasChanged(form) {
for (var field in form) {
if (field.meta.dirty === true) {
return true;
}
}
return false;
}
Should update problem
observable pa+ern
const form = { /* ... */ };
Object.observe(form, changes => {
doSomethingExpensive(form);
});
form.firstName = 'Maciej';
form.lastName = 'Komorowski';
form.profession = 'Brogrammer'; // Not true :)
Should update problem
immutable
let currentForm = { /* ... */ };
function hasChanged(form) {
return currentForm !== form;
}
Memoiza(on example
function memoize(fn) {
var cache = {};
return function (arg) {
var hash = arg === Object(arg)
? JSON.stringify(arg) // Wat?
: arg;
return hash in cache ?
cache[hash] :
(cache[hash] = fn.call(this, arg));
}
}
Memoiza(on example
function rawSum(list) {
return list.reduce((a, b) => a + b)
}
const sum = memoize(rawSum);
const array = [0, 1, ...1000000];
sum(array); // 89 ms
rawSum(array); // 51 ms
sum(array); // 42 ms
Advantages of immutability
! No defensive copies
! Can be faster
! Be3er for concurrency (no deadlocks)
Explore func-onal programing❗
It's worth it
Contact
Maciej Komorowski
@komomc
Quiz
What f does?
f = 0 : 1 : zipWith (+) f (tail f)
Answer
Generates Fibonacci sequence
> let fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
> take 11 fibs
[0,1,1,2,3,5,8,13,21,34,55]

More Related Content

What's hot

Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax BasicsRichard Paul
 
Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0Eyal Vardi
 
How to Create a l10n Payroll Structure
How to Create a l10n Payroll StructureHow to Create a l10n Payroll Structure
How to Create a l10n Payroll StructureOdoo
 
Symfony World - Symfony components and design patterns
Symfony World - Symfony components and design patternsSymfony World - Symfony components and design patterns
Symfony World - Symfony components and design patternsŁukasz Chruściel
 
G*ワークショップ in 仙台 Grails(とことん)入門
G*ワークショップ in 仙台 Grails(とことん)入門G*ワークショップ in 仙台 Grails(とことん)入門
G*ワークショップ in 仙台 Grails(とことん)入門Tsuyoshi Yamamoto
 
Dutch php a short tale about state machine
Dutch php   a short tale about state machineDutch php   a short tale about state machine
Dutch php a short tale about state machineŁukasz Chruściel
 
exportDisabledUsersRemoveMailbox
exportDisabledUsersRemoveMailboxexportDisabledUsersRemoveMailbox
exportDisabledUsersRemoveMailboxDaniel Gilhousen
 
Relay Modern: architecture and workflow
Relay Modern: architecture and workflowRelay Modern: architecture and workflow
Relay Modern: architecture and workflowAlex Alexeev
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and httpAlexe Bogdan
 
05 communications
05 communications05 communications
05 communicationsmemeapps
 
Angular server-side communication
Angular server-side communicationAngular server-side communication
Angular server-side communicationAlexe Bogdan
 
Impact of the New ORM on Your Modules
Impact of the New ORM on Your ModulesImpact of the New ORM on Your Modules
Impact of the New ORM on Your ModulesOdoo
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 formsEyal Vardi
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Eyal Vardi
 

What's hot (20)

Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
Lecture04
Lecture04Lecture04
Lecture04
 
Class ‘increment’
Class ‘increment’Class ‘increment’
Class ‘increment’
 
Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0
 
How to Create a l10n Payroll Structure
How to Create a l10n Payroll StructureHow to Create a l10n Payroll Structure
How to Create a l10n Payroll Structure
 
Symfony World - Symfony components and design patterns
Symfony World - Symfony components and design patternsSymfony World - Symfony components and design patterns
Symfony World - Symfony components and design patterns
 
G*ワークショップ in 仙台 Grails(とことん)入門
G*ワークショップ in 仙台 Grails(とことん)入門G*ワークショップ in 仙台 Grails(とことん)入門
G*ワークショップ in 仙台 Grails(とことん)入門
 
Dutch php a short tale about state machine
Dutch php   a short tale about state machineDutch php   a short tale about state machine
Dutch php a short tale about state machine
 
exportDisabledUsersRemoveMailbox
exportDisabledUsersRemoveMailboxexportDisabledUsersRemoveMailbox
exportDisabledUsersRemoveMailbox
 
Relay Modern: architecture and workflow
Relay Modern: architecture and workflowRelay Modern: architecture and workflow
Relay Modern: architecture and workflow
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 
05 communications
05 communications05 communications
05 communications
 
Protocol-Oriented MVVM
Protocol-Oriented MVVMProtocol-Oriented MVVM
Protocol-Oriented MVVM
 
ZIO Queue
ZIO QueueZIO Queue
ZIO Queue
 
Angular server-side communication
Angular server-side communicationAngular server-side communication
Angular server-side communication
 
Impact of the New ORM on Your Modules
Impact of the New ORM on Your ModulesImpact of the New ORM on Your Modules
Impact of the New ORM on Your Modules
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Cocoa heads 09112017
Cocoa heads 09112017Cocoa heads 09112017
Cocoa heads 09112017
 
Berlin meetup
Berlin meetupBerlin meetup
Berlin meetup
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 

Viewers also liked

День банкира
День банкираДень банкира
День банкираlibusue
 
Visual Media Portfolio
Visual Media PortfolioVisual Media Portfolio
Visual Media PortfolioLA20177
 
Gdz 11 klas_geometrija_o_v_pogorelov
Gdz 11 klas_geometrija_o_v_pogorelovGdz 11 klas_geometrija_o_v_pogorelov
Gdz 11 klas_geometrija_o_v_pogorelovLucky Alex
 
Star software marketing plan
Star software marketing planStar software marketing plan
Star software marketing planAftab Younas
 
Onderwijs binnen inclusieve samenleving koca
Onderwijs binnen inclusieve samenleving   kocaOnderwijs binnen inclusieve samenleving   koca
Onderwijs binnen inclusieve samenleving kocatom_vermeulen
 
Harrypotty preview
Harrypotty previewHarrypotty preview
Harrypotty previewFrank Muniz
 
Rae Aspectos Morfologicos de la Lengua
Rae Aspectos Morfologicos de la LenguaRae Aspectos Morfologicos de la Lengua
Rae Aspectos Morfologicos de la LenguaAdriana Martinez
 
We aim to cheese - LB
We aim to cheese - LBWe aim to cheese - LB
We aim to cheese - LBTim Ashton
 
13APortfolioKeestanWilles
13APortfolioKeestanWilles13APortfolioKeestanWilles
13APortfolioKeestanWillesKeestan Willes
 
IMD MBA Class Profiles
IMD MBA Class ProfilesIMD MBA Class Profiles
IMD MBA Class ProfilesSameer Saurabh
 
Content Marketing: Your Digital Salesperson
Content Marketing: Your Digital SalespersonContent Marketing: Your Digital Salesperson
Content Marketing: Your Digital SalespersonNextLeft
 

Viewers also liked (16)

ThesisProposal
ThesisProposalThesisProposal
ThesisProposal
 
علت نیاز به وب سایت
علت نیاز به وب سایتعلت نیاز به وب سایت
علت نیاز به وب سایت
 
День банкира
День банкираДень банкира
День банкира
 
Visual Media Portfolio
Visual Media PortfolioVisual Media Portfolio
Visual Media Portfolio
 
Gdz 11 klas_geometrija_o_v_pogorelov
Gdz 11 klas_geometrija_o_v_pogorelovGdz 11 klas_geometrija_o_v_pogorelov
Gdz 11 klas_geometrija_o_v_pogorelov
 
Star software marketing plan
Star software marketing planStar software marketing plan
Star software marketing plan
 
Onderwijs binnen inclusieve samenleving koca
Onderwijs binnen inclusieve samenleving   kocaOnderwijs binnen inclusieve samenleving   koca
Onderwijs binnen inclusieve samenleving koca
 
Harrypotty preview
Harrypotty previewHarrypotty preview
Harrypotty preview
 
Rae Aspectos Morfologicos de la Lengua
Rae Aspectos Morfologicos de la LenguaRae Aspectos Morfologicos de la Lengua
Rae Aspectos Morfologicos de la Lengua
 
We aim to cheese - LB
We aim to cheese - LBWe aim to cheese - LB
We aim to cheese - LB
 
13APortfolioKeestanWilles
13APortfolioKeestanWilles13APortfolioKeestanWilles
13APortfolioKeestanWilles
 
IMD MBA Class Profiles
IMD MBA Class ProfilesIMD MBA Class Profiles
IMD MBA Class Profiles
 
Газпром-нефть
Газпром-нефтьГазпром-нефть
Газпром-нефть
 
IngléS
IngléSIngléS
IngléS
 
Content Marketing: Your Digital Salesperson
Content Marketing: Your Digital SalespersonContent Marketing: Your Digital Salesperson
Content Marketing: Your Digital Salesperson
 
Final task Unit 5
Final task Unit 5Final task Unit 5
Final task Unit 5
 

Similar to Func up your code

Perkenalan ReasonML
Perkenalan ReasonMLPerkenalan ReasonML
Perkenalan ReasonMLRiza Fahmi
 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?Federico Tomassetti
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
Part APurposeThis laboratory provides some experience work.docx
Part APurposeThis laboratory provides some experience work.docxPart APurposeThis laboratory provides some experience work.docx
Part APurposeThis laboratory provides some experience work.docxdewhirstichabod
 
Introduction to ReasonML
Introduction to ReasonMLIntroduction to ReasonML
Introduction to ReasonMLRiza Fahmi
 
Chaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscoreChaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscoreNicolas Carlo
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wildJoe Morgan
 
Writing Your App Swiftly
Writing Your App SwiftlyWriting Your App Swiftly
Writing Your App SwiftlySommer Panage
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreNicolas Carlo
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web ModuleMorgan Cheng
 
Gerenciamento de estado no Angular com NgRx
Gerenciamento de estado no Angular com NgRxGerenciamento de estado no Angular com NgRx
Gerenciamento de estado no Angular com NgRxLoiane Groner
 
Gutenberg sous le capot, modules réutilisables
Gutenberg sous le capot, modules réutilisablesGutenberg sous le capot, modules réutilisables
Gutenberg sous le capot, modules réutilisablesRiad Benguella
 
ViewController.swift Calculatorimport Cocoaimport UIKit.pdf
 ViewController.swift Calculatorimport Cocoaimport UIKit.pdf ViewController.swift Calculatorimport Cocoaimport UIKit.pdf
ViewController.swift Calculatorimport Cocoaimport UIKit.pdfarasanlethers
 
Battle of React State Managers in frontend applications
Battle of React State Managers in frontend applicationsBattle of React State Managers in frontend applications
Battle of React State Managers in frontend applicationsEvangelia Mitsopoulou
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScriptRasan Samarasinghe
 
Funcitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayFuncitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayNatasha Murashev
 

Similar to Func up your code (20)

Advanced redux
Advanced reduxAdvanced redux
Advanced redux
 
Perkenalan ReasonML
Perkenalan ReasonMLPerkenalan ReasonML
Perkenalan ReasonML
 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Part APurposeThis laboratory provides some experience work.docx
Part APurposeThis laboratory provides some experience work.docxPart APurposeThis laboratory provides some experience work.docx
Part APurposeThis laboratory provides some experience work.docx
 
Introduction to ReasonML
Introduction to ReasonMLIntroduction to ReasonML
Introduction to ReasonML
 
Chaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscoreChaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscore
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wild
 
Writing Your App Swiftly
Writing Your App SwiftlyWriting Your App Swiftly
Writing Your App Swiftly
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
 
Gerenciamento de estado no Angular com NgRx
Gerenciamento de estado no Angular com NgRxGerenciamento de estado no Angular com NgRx
Gerenciamento de estado no Angular com NgRx
 
ReactJS
ReactJSReactJS
ReactJS
 
Gutenberg sous le capot, modules réutilisables
Gutenberg sous le capot, modules réutilisablesGutenberg sous le capot, modules réutilisables
Gutenberg sous le capot, modules réutilisables
 
ViewController.swift Calculatorimport Cocoaimport UIKit.pdf
 ViewController.swift Calculatorimport Cocoaimport UIKit.pdf ViewController.swift Calculatorimport Cocoaimport UIKit.pdf
ViewController.swift Calculatorimport Cocoaimport UIKit.pdf
 
Battle of React State Managers in frontend applications
Battle of React State Managers in frontend applicationsBattle of React State Managers in frontend applications
Battle of React State Managers in frontend applications
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Vuejs testing
Vuejs testingVuejs testing
Vuejs testing
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
 
Funcitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayFuncitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional Way
 

Recently uploaded

WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2
 
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...WSO2
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2
 
WSO2CON 2024 - Software Engineering for Digital Businesses
WSO2CON 2024 - Software Engineering for Digital BusinessesWSO2CON 2024 - Software Engineering for Digital Businesses
WSO2CON 2024 - Software Engineering for Digital BusinessesWSO2
 
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdfAzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdfryanfarris8
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
WSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration ToolingWSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration ToolingWSO2
 
WSO2CON 2024 - Architecting AI in the Enterprise: APIs and Applications
WSO2CON 2024 - Architecting AI in the Enterprise: APIs and ApplicationsWSO2CON 2024 - Architecting AI in the Enterprise: APIs and Applications
WSO2CON 2024 - Architecting AI in the Enterprise: APIs and ApplicationsWSO2
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
WSO2CON 2024 - OSU & WSO2: A Decade Journey in Integration & Innovation
WSO2CON 2024 - OSU & WSO2: A Decade Journey in Integration & InnovationWSO2CON 2024 - OSU & WSO2: A Decade Journey in Integration & Innovation
WSO2CON 2024 - OSU & WSO2: A Decade Journey in Integration & InnovationWSO2
 
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...WSO2
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 

Recently uploaded (20)

WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AI
 
WSO2CON 2024 - Software Engineering for Digital Businesses
WSO2CON 2024 - Software Engineering for Digital BusinessesWSO2CON 2024 - Software Engineering for Digital Businesses
WSO2CON 2024 - Software Engineering for Digital Businesses
 
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdfAzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
WSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration ToolingWSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration Tooling
 
WSO2CON 2024 - Architecting AI in the Enterprise: APIs and Applications
WSO2CON 2024 - Architecting AI in the Enterprise: APIs and ApplicationsWSO2CON 2024 - Architecting AI in the Enterprise: APIs and Applications
WSO2CON 2024 - Architecting AI in the Enterprise: APIs and Applications
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
WSO2CON 2024 - OSU & WSO2: A Decade Journey in Integration & Innovation
WSO2CON 2024 - OSU & WSO2: A Decade Journey in Integration & InnovationWSO2CON 2024 - OSU & WSO2: A Decade Journey in Integration & Innovation
WSO2CON 2024 - OSU & WSO2: A Decade Journey in Integration & Innovation
 
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - Kanchana
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 

Func up your code

  • 1. Func up your code Maciej Komorowski
  • 2. What is func%onal programming?
  • 3. Func%onal programming is programming paradigm [...] that treats computa%on as the evalua%on of mathema&cal func&ons and avoids changing-state and mutable data. — Wikipedia
  • 4. Pillars of FP • Higher-order func0ons (e.g. map) • Immutable data • Lazy evalua0on • Pure func0ons • Recursion
  • 5. Pure func)on ! Always evaluates the same result value given the same arguments ! Does not cause any seman5cally observable side effect, such as muta5on of mutable objects
  • 6. Pure func)on examples // Pure function add(a, b) { return a + b; } // Impure Math.random(); // Impure const items = [] function addItem(item) { return items.push(item); }
  • 8. State muta(on in OOP ! Relies heavily on encapsula)on ! Has hidden nature ! Brings nondeterminism ! Root cause of doom
  • 9. Brogrammer1 State muta)on example A brogrammer is [...] a slang term for a macho, male programmer. A brogrammer might self-describe as a sociable programmer. — Wikipedia 1 Frans Hals, Oil on canvas, 1630. Source: classicprogrammerpain;ngs
  • 10. What brogrammer does? • drinkBeer • talk
  • 11. Stateful implementa*on class Brogrammer { constructor() { this.beers = 0; } drinkBeer() { /* ... */ } talk() { /* ... */ } }
  • 12. Stateful – drinkBeer it('increment number of drunk beers', () => { expect(brogrammer.drinkBeer()).toEqual(1); expect(brogrammer.drinkBeer()).toEqual(2); }); // Inside Brogrammer class drinkBeer() { return this.beers += 1; // encapsulates 'beers' }
  • 13. Stateful – talk tests it('says "Beer me up!" before drinking', () => { expect(brogrammer.talk()).toEqual("Beer me up!"); }); it('says "Yummy" after 1st beer', () => { brogrammer.drinkBeer(); expect(brogrammer.talk()).toEqual("Yummy"); }); it('says "I a<M dRuNk" after 10th beer', () => { brogrammer.drinkBeer(); // 8 x brogrammer.drinkBeer(); brogrammer.drinkBeer(); expect(brogrammer.talk()).toEqual("I a<M dRuNk"); });
  • 14. Stateful – talk implementa+on // Inside Brogrammer class talk() { return ({ 0: 'Beer me up!', 1: 'Yummy', // ... 10: 'I a<M dRuNk', })[this.beers] || ''; }
  • 15. How to remove state? Single source of truth
  • 16. Naïve stateless – implementa+on class Brogrammer { constructor(store) { this.store = store; } // ... }
  • 17. Naïve stateless – drinkBeer tests it('increment number of drunk beers', () => { const store = { beers: 0 }; const brogrammer = new Brogrammer(store); brogrammer.drinkBeer(); expect(store.beers).toEqual(1); });
  • 18. Naïve stateless – drinkBeer implementa+on // Inside Brogrammer class drinkBeer() { return this.store.beers += 1; }
  • 19. Naïve stateless – talk tests it('says "I a<M dRuNk" after 10th beer', () => { const store = { beers: 10 }; const brogrammer = new Brogrammer(store); expect(brogrammer.talk()).toEqual("I a<M dRuNk"); });
  • 20. Naïve stateless – talk implementa+on // Inside Brogrammer class talk() { return ({ 0: 'Beer me up!', 1: 'Yummy', // ... 10: 'I a<M dRuNk', })[this.store.beers] || ''; }
  • 21. Solu%on review ! Removed state from the Brogrammer ! Easier tes2ng " Lost encapsula-on
  • 22. How to improve? The Redux way
  • 24. Three Principles of Redux3 ! Single source of truth ! State is read-only ! Changes are made with pure func)ons 3 Source: Redux
  • 25. Three Principles of Redux Single source of truth console.log(store.getState()); // { // brogrammer: { // beers: 0 // } // }
  • 26. Three Principles of Redux State is read-only store.dispatch({ type: 'INCREMENT_BEERS', });
  • 27. Three Principles of Redux Changes are made with pure func3ons function brogrammer(state = {}, action) { switch (action.type) { case 'SET_BEERS': return { ...state, beers: 5, }; // case ... } }
  • 28. Redux – incrementBeers ac%on it('returns action with type INCREMENT_BEERS', () => { const action = incrementBeers(); expect(action).toEqual({ type: 'INCREMENT_BEERS' }); });
  • 29. Redux – incrementBeers ac%on const incrementBeers = () => ({ type: 'INCREMENT_BEERS', });
  • 30. Redux – brogrammer reducer it('returns state with incremented beers', () => { const state = { beers: 0 }; const action = incrementBeers(); const nextState = brogrammer(state, action); expect(nextState).toEqual({ beers: 1 }); });
  • 31. Redux – brogrammer reducer implementa)on const brogrammer = (state = {}, action) => { switch (action.type) { case 'INCREMENT_BEERS': return { ...state, beers: state.beers + 1 }; default: return state } }
  • 32. Redux – drinkBeer tests it('increment number of drunk beers', () => { const store = createStore({ beers: 0 }); const brogrammer = new Brogrammer(store); brogrammer.drinkBeer(); expect(store.dispatch) .toHaveBeenCalledWith(incrementBeers()); });
  • 33. Redux – drinkBeer implementa+on // Inside Brogrammer class drinkBeer() { return this.store.dispatch(incrementBeers()); }
  • 34. Redux – talk tests it('says "I a<M dRuNk" after 10th beer', () => { const store = createStore({ beers: 10 }); const brogrammer = new Brogrammer(store); expect(brogrammer.talk()).toEqual("I a<M dRuNk"); });
  • 35. Redux – talk implementa+on // Inside Brogrammer class talk() { return ({ 0: 'Beer me up!', 1: 'Yummy', // ... 10: 'I a<M dRuNk', })[this.store.get('beers')] || ''; }
  • 36. Solu%on review ! Easy tes(ng ! Be,er separa(on ! Explicit state changes ! Full control over state
  • 37. A few thoughts on Redux
  • 39. Mutable vs immutable // Mutable const items = ['foo']; items.push('bar'); items.push('baz'); console.log(items); // ["foo", "bar", "baz"]
  • 40. Mutable vs immutable // Immutable via immutable-js const items = Immutable.List.of('foo'); items.push('bar'); items.push('baz'); console.log(items.toArray()); // ["foo"] console.log(items.push('bar').push('baz').toArray()); // ["foo", "bar", "baz"]
  • 41. What about performance?5 5 Source: React.js Conf 2015 - Immutable Data and React
  • 42. Performance benchmark Array push 1,000,000 items: var list = []; for (var i = 0; i < 1000000; i++) { list.push(i); } 83 ms
  • 43. Performance benchmark Mori immutable vector conj 1,000,000 items: var list = mori.vector(); for (var i = 0; i < 1000000; i++) { mori.conj(list, i); } 288 ms
  • 44. Should update problem const form = { /* ... */ }; function submit(form) { if (hasChanged(form)) { doSomethingExpensive(form); } }
  • 45. Should update problem versioning let currentFormVersion; function hasChanged(form) { const formVersion = md5(JSON.stringify(form)); return formVersion !== currentFormVersion; }
  • 46. Should update problem dirty bits function hasChanged(form) { for (var field in form) { if (field.meta.dirty === true) { return true; } } return false; }
  • 47. Should update problem observable pa+ern const form = { /* ... */ }; Object.observe(form, changes => { doSomethingExpensive(form); }); form.firstName = 'Maciej'; form.lastName = 'Komorowski'; form.profession = 'Brogrammer'; // Not true :)
  • 48. Should update problem immutable let currentForm = { /* ... */ }; function hasChanged(form) { return currentForm !== form; }
  • 49. Memoiza(on example function memoize(fn) { var cache = {}; return function (arg) { var hash = arg === Object(arg) ? JSON.stringify(arg) // Wat? : arg; return hash in cache ? cache[hash] : (cache[hash] = fn.call(this, arg)); } }
  • 50. Memoiza(on example function rawSum(list) { return list.reduce((a, b) => a + b) } const sum = memoize(rawSum); const array = [0, 1, ...1000000]; sum(array); // 89 ms rawSum(array); // 51 ms sum(array); // 42 ms
  • 51. Advantages of immutability ! No defensive copies ! Can be faster ! Be3er for concurrency (no deadlocks)
  • 54. Quiz What f does? f = 0 : 1 : zipWith (+) f (tail f)
  • 55. Answer Generates Fibonacci sequence > let fibs = 0 : 1 : zipWith (+) fibs (tail fibs) > take 11 fibs [0,1,1,2,3,5,8,13,21,34,55]