SlideShare a Scribd company logo
Pure Functions
Leon Maia
https://leonmaia.com
Agenda
•What’s a function?
•What’s a pure function?
•What’s a side effect?
•Referential transparency.
•Keep it simple.
•Examples.
•The trouble with shared state.
2
What’s a function?
3
A function is something that takes an input, and
produces some output.
function sum(a, b) {
return a+b;
}
For example, this is a function that takes two numbers
and returns the sum.
What’s a pure function?
4
A pure function is a function which:
• Given the same input, will always return the same
output.
• Produces no side effects.
• Relies on no external state.
What’s a side effect?
5
Side effects may include, but are not limited to:
• Changing the file system.
• Inserting a record into a database.
• Making an http call.
• Mutations.
• Printing to the screen / logging.
• Obtaining user input.
• Accessing system state.
Referential transparency.
6
A function in algebra: f(x) = 2x
> const double = x => x * 2;
Since `double` is a pure function we can replace
`double(5)` with 10 without changing the meaning.
So, `console.log(double(5));` is the same as
`console.log(10);`
Keep it simple.
7
Pure functions take some input and return some output
based on that input. They are the simplest reusable
building blocks of code in a program:
• KISS (Keep It Simple, Stupid)
Pure functions are stupid simple in the best possible
way.
Examples:
8
Examples:
9
In summary.
• Extremely independent.
• Easy to move around.
• Refactor.
• Easy to reorganize in your code.
• Gives more flexibility.
• Adaptable to future changes.
• Easy to test.
10
The trouble with shared state
11
The trouble with shared state
• Reliant on sequences which vary depending on indeterministic factors.
• The output is impossible to predict.
• Impossible to properly test.
• Impossible to fully understand.
12
“
| Confidential
There is no non-determinism without mutable states. There
is no race condition or deadlock without mutable states.
Mutable states are the root of the problem.
13
— Martin Odersky
| Confidential
non-determinism = parallel processing + mutable state
14
Recipe for bugs.
• A single threaded JS engine does not imply that there is no
concurrency.
• API I/O, event listeners, web workers, iframes, and timeouts.
Combine that with shared state, and you’ve got a recipe for bugs.
15
“
| Confidential
Shared mutable state and parallel processing doesn't go
together at all. If you do not use proper synchronization you
will create extremely difficult to find bugs and your
programs are basically broken even if they appear to work
just fine in most cases.
16
| Confidential
Thanks!
17

More Related Content

What's hot

The Perks and Perils of the Singleton Design Pattern
The Perks and Perils of the Singleton Design PatternThe Perks and Perils of the Singleton Design Pattern
The Perks and Perils of the Singleton Design Pattern
BADR
 
Brixton Library Technology Initiative Week1 Recap
Brixton Library Technology Initiative Week1 RecapBrixton Library Technology Initiative Week1 Recap
Brixton Library Technology Initiative Week1 Recap
Basil Bibi
 
Assic 8th Lecture
Assic 8th LectureAssic 8th Lecture
Assic 8th Lecture
babak danyal
 
Hipster Oriented Programming
Hipster Oriented ProgrammingHipster Oriented Programming
Hipster Oriented Programming
Jens Ravens
 
RxSwift
RxSwiftRxSwift
RxSwift
Sally Ahmed
 
From Imperative to Functional Programming (for Absolute Beginners)
From Imperative to Functional Programming (for Absolute Beginners)From Imperative to Functional Programming (for Absolute Beginners)
From Imperative to Functional Programming (for Absolute Beginners)
Alex Bunardzic
 
Java script best practices v4
Java script best practices v4Java script best practices v4
Java script best practices v4
Thor Jørund Nydal
 
Clean code quotes - Citações e provocações
Clean code quotes - Citações e provocaçõesClean code quotes - Citações e provocações
Clean code quotes - Citações e provocações
André de Fontana Ignacio
 
Основы функционального JS
Основы функционального JSОсновы функционального JS
Основы функционального JS
Анна Луць
 
JavaScript Introductin to Functions
JavaScript Introductin to FunctionsJavaScript Introductin to Functions
JavaScript Introductin to Functions
Charles Russell
 
React koans
React koansReact koans
React koans
Alex Lobera
 

What's hot (11)

The Perks and Perils of the Singleton Design Pattern
The Perks and Perils of the Singleton Design PatternThe Perks and Perils of the Singleton Design Pattern
The Perks and Perils of the Singleton Design Pattern
 
Brixton Library Technology Initiative Week1 Recap
Brixton Library Technology Initiative Week1 RecapBrixton Library Technology Initiative Week1 Recap
Brixton Library Technology Initiative Week1 Recap
 
Assic 8th Lecture
Assic 8th LectureAssic 8th Lecture
Assic 8th Lecture
 
Hipster Oriented Programming
Hipster Oriented ProgrammingHipster Oriented Programming
Hipster Oriented Programming
 
RxSwift
RxSwiftRxSwift
RxSwift
 
From Imperative to Functional Programming (for Absolute Beginners)
From Imperative to Functional Programming (for Absolute Beginners)From Imperative to Functional Programming (for Absolute Beginners)
From Imperative to Functional Programming (for Absolute Beginners)
 
Java script best practices v4
Java script best practices v4Java script best practices v4
Java script best practices v4
 
Clean code quotes - Citações e provocações
Clean code quotes - Citações e provocaçõesClean code quotes - Citações e provocações
Clean code quotes - Citações e provocações
 
Основы функционального JS
Основы функционального JSОсновы функционального JS
Основы функционального JS
 
JavaScript Introductin to Functions
JavaScript Introductin to FunctionsJavaScript Introductin to Functions
JavaScript Introductin to Functions
 
React koans
React koansReact koans
React koans
 

Similar to Pure functions using Javascript.

Functional programmning
Functional programmningFunctional programmning
Functional programmning
Ayat_Khraisat
 
2020-Feb: Testing: Cables and Chains
2020-Feb: Testing: Cables and Chains2020-Feb: Testing: Cables and Chains
2020-Feb: Testing: Cables and Chains
Mark Windholtz
 
Working Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in PracticeWorking Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in Practice
Amar Shah
 
Deterministic behaviour and performance in trading systems
Deterministic behaviour and performance in trading systemsDeterministic behaviour and performance in trading systems
Deterministic behaviour and performance in trading systems
Peter Lawrey
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with Redux
FITC
 
MongoDB World 2018: Tutorial - MongoDB Meets Chaos Monkey
MongoDB World 2018: Tutorial - MongoDB Meets Chaos MonkeyMongoDB World 2018: Tutorial - MongoDB Meets Chaos Monkey
MongoDB World 2018: Tutorial - MongoDB Meets Chaos Monkey
MongoDB
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
Martin Odersky
 
Declarative Network Configuration
Declarative Network Configuration Declarative Network Configuration
Declarative Network Configuration
Salesforce Engineering
 
How Functional Programming Made Me a Better Developer
How Functional Programming Made Me a Better DeveloperHow Functional Programming Made Me a Better Developer
How Functional Programming Made Me a Better Developer
Cameron Presley
 
Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...
Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...
Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...
Sargis Sargsyan
 
Generating unit tests based on user logs
Generating unit tests based on user logsGenerating unit tests based on user logs
Generating unit tests based on user logs
Rick Wicker
 
System Accidents: Understanding Common Accidents
System Accidents: Understanding Common AccidentsSystem Accidents: Understanding Common Accidents
System Accidents: Understanding Common Accidents
Galen Emery, CISSP
 
Concurrency - Why it's hard ?
Concurrency - Why it's hard ?Concurrency - Why it's hard ?
Concurrency - Why it's hard ?
Ramith Jayasinghe
 
Determinism in finance
Determinism in financeDeterminism in finance
Determinism in finance
Peter Lawrey
 
Why Concurrency is hard ?
Why Concurrency is hard ?Why Concurrency is hard ?
Why Concurrency is hard ?
Ramith Jayasinghe
 
Error in hadoop
Error in hadoopError in hadoop
Error in hadoop
Len Bass
 
Allyourbase
AllyourbaseAllyourbase
Allyourbase
Alex Scotti
 
Qardio experience with Core Data
Qardio experience with Core DataQardio experience with Core Data
Qardio experience with Core Data
Dmitrii Ivanov
 
Better Page Object Handling with Loadable Component Pattern
Better Page Object Handling with Loadable Component PatternBetter Page Object Handling with Loadable Component Pattern
Better Page Object Handling with Loadable Component Pattern
SQALab
 
DBmaestro's State of the Database Continuous Delivery Survey- Findings Revealed
DBmaestro's State of the Database Continuous Delivery Survey- Findings RevealedDBmaestro's State of the Database Continuous Delivery Survey- Findings Revealed
DBmaestro's State of the Database Continuous Delivery Survey- Findings Revealed
DBmaestro - Database DevOps
 

Similar to Pure functions using Javascript. (20)

Functional programmning
Functional programmningFunctional programmning
Functional programmning
 
2020-Feb: Testing: Cables and Chains
2020-Feb: Testing: Cables and Chains2020-Feb: Testing: Cables and Chains
2020-Feb: Testing: Cables and Chains
 
Working Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in PracticeWorking Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in Practice
 
Deterministic behaviour and performance in trading systems
Deterministic behaviour and performance in trading systemsDeterministic behaviour and performance in trading systems
Deterministic behaviour and performance in trading systems
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with Redux
 
MongoDB World 2018: Tutorial - MongoDB Meets Chaos Monkey
MongoDB World 2018: Tutorial - MongoDB Meets Chaos MonkeyMongoDB World 2018: Tutorial - MongoDB Meets Chaos Monkey
MongoDB World 2018: Tutorial - MongoDB Meets Chaos Monkey
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
Declarative Network Configuration
Declarative Network Configuration Declarative Network Configuration
Declarative Network Configuration
 
How Functional Programming Made Me a Better Developer
How Functional Programming Made Me a Better DeveloperHow Functional Programming Made Me a Better Developer
How Functional Programming Made Me a Better Developer
 
Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...
Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...
Better Page Object Handling with Loadable Component Pattern - SQA Days 20, Be...
 
Generating unit tests based on user logs
Generating unit tests based on user logsGenerating unit tests based on user logs
Generating unit tests based on user logs
 
System Accidents: Understanding Common Accidents
System Accidents: Understanding Common AccidentsSystem Accidents: Understanding Common Accidents
System Accidents: Understanding Common Accidents
 
Concurrency - Why it's hard ?
Concurrency - Why it's hard ?Concurrency - Why it's hard ?
Concurrency - Why it's hard ?
 
Determinism in finance
Determinism in financeDeterminism in finance
Determinism in finance
 
Why Concurrency is hard ?
Why Concurrency is hard ?Why Concurrency is hard ?
Why Concurrency is hard ?
 
Error in hadoop
Error in hadoopError in hadoop
Error in hadoop
 
Allyourbase
AllyourbaseAllyourbase
Allyourbase
 
Qardio experience with Core Data
Qardio experience with Core DataQardio experience with Core Data
Qardio experience with Core Data
 
Better Page Object Handling with Loadable Component Pattern
Better Page Object Handling with Loadable Component PatternBetter Page Object Handling with Loadable Component Pattern
Better Page Object Handling with Loadable Component Pattern
 
DBmaestro's State of the Database Continuous Delivery Survey- Findings Revealed
DBmaestro's State of the Database Continuous Delivery Survey- Findings RevealedDBmaestro's State of the Database Continuous Delivery Survey- Findings Revealed
DBmaestro's State of the Database Continuous Delivery Survey- Findings Revealed
 

Recently uploaded

原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
ydzowc
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
VANDANAMOHANGOUDA
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
RamonNovais6
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
Applications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdfApplications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdf
Atif Razi
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
ElakkiaU
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
GauravCar
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
UReason
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
abbyasa1014
 
integral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdfintegral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdf
gaafergoudaay7aga
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
LAXMAREDDY22
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
gowrishankartb2005
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
AI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptxAI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptx
architagupta876
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
shadow0702a
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
21UME003TUSHARDEB
 
Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
bijceesjournal
 

Recently uploaded (20)

原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
Applications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdfApplications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdf
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
 
integral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdfintegral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdf
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
AI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptxAI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptx
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
 
Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
 

Pure functions using Javascript.

  • 2. Agenda •What’s a function? •What’s a pure function? •What’s a side effect? •Referential transparency. •Keep it simple. •Examples. •The trouble with shared state. 2
  • 3. What’s a function? 3 A function is something that takes an input, and produces some output. function sum(a, b) { return a+b; } For example, this is a function that takes two numbers and returns the sum.
  • 4. What’s a pure function? 4 A pure function is a function which: • Given the same input, will always return the same output. • Produces no side effects. • Relies on no external state.
  • 5. What’s a side effect? 5 Side effects may include, but are not limited to: • Changing the file system. • Inserting a record into a database. • Making an http call. • Mutations. • Printing to the screen / logging. • Obtaining user input. • Accessing system state.
  • 6. Referential transparency. 6 A function in algebra: f(x) = 2x > const double = x => x * 2; Since `double` is a pure function we can replace `double(5)` with 10 without changing the meaning. So, `console.log(double(5));` is the same as `console.log(10);`
  • 7. Keep it simple. 7 Pure functions take some input and return some output based on that input. They are the simplest reusable building blocks of code in a program: • KISS (Keep It Simple, Stupid) Pure functions are stupid simple in the best possible way.
  • 10. In summary. • Extremely independent. • Easy to move around. • Refactor. • Easy to reorganize in your code. • Gives more flexibility. • Adaptable to future changes. • Easy to test. 10
  • 11. The trouble with shared state 11
  • 12. The trouble with shared state • Reliant on sequences which vary depending on indeterministic factors. • The output is impossible to predict. • Impossible to properly test. • Impossible to fully understand. 12
  • 13. “ | Confidential There is no non-determinism without mutable states. There is no race condition or deadlock without mutable states. Mutable states are the root of the problem. 13 — Martin Odersky
  • 14. | Confidential non-determinism = parallel processing + mutable state 14
  • 15. Recipe for bugs. • A single threaded JS engine does not imply that there is no concurrency. • API I/O, event listeners, web workers, iframes, and timeouts. Combine that with shared state, and you’ve got a recipe for bugs. 15
  • 16. “ | Confidential Shared mutable state and parallel processing doesn't go together at all. If you do not use proper synchronization you will create extremely difficult to find bugs and your programs are basically broken even if they appear to work just fine in most cases. 16