SlideShare a Scribd company logo
FUNCTIONAL
PRINCIPLES
Introduction to Functional Programming
and Java 8
WHY ?
WHY FUNCTIONAL PROGRAMMING ? / MOORE’S LAW
WHY FUNCTIONAL PROGRAMMING ? / MULTI CORE TREND
WHY FUNCTIONAL PROGRAMMING ? / SOME HISTORY
WHAT ?
• A programming paradigm where
functions are first-class entities
• The main concepts are:
1. programming with functions
2. avoid mutation
• A new way of thinking
WHAT IS FP ?
• Object Immutability
• Functions:
– as first class citizens
– no side effects (Pure functions)
– Higher Order Functions
• No loops
• Lazy evaluation
WHAT IS FP ? / FUNCTIONAL PRINCIPLES
• Easier parallelization
• Less code
• Easy testing
• Results instead of steps
• Easy to understand code
WHAT IS FP ? / WHAT YOU GET ?
HOW ?
IMMUTABILITY
An immutable object is an object
whose state cannot be modified
after it is created
IMMUTABLE OBJECTS
“Classes should be immutable unless
there’s very good reason to make them
mutable… If a class cannot be made
immutable, limit its mutability as much
as possible”
Joshua Bloch
IMMUTABLE OBJECTS
IMMUTABLE OBJECTS / JAVA
IMMUTABLE OBJECTS / DEFENSIVE COPY
IMMUTABLE OBJECTS / OTHER FUNCTIONAL LANGUAGES
IMMUTABLE OBJECTS / OTHER FUNCTIONAL LANGUAGES
IMMUTABLE OBJECTS / HOW TO CHANGE ?
IMMUTABLE OBJECTS / PARALLELISM
•are thread-safe
•are simple to construct
•easy to test
•easy to use
•favors caching
IMMUTABLE OBJECTS / PROS
• Large object graphs
• Memory consumption
• Extra garbage collection cycles needed
IMMUTABLE OBJECTS / CONS
FUNCTIONS
F : X → Y
HIGHER ORDER
FUNCTIONS
(HOF)
HOF = functions that can take other
functions as arguments and / or
return other functions as result
HIGHER ORDER FUNCTIONS / DEFINITION
HIGHER ORDER FUNCTIONS / FIRST CLASS CITIZENS
HIGHER ORDER FUNCTIONS / FUNCTIONS AS PARAMS
HIGHER ORDER FUNCTIONS / RETURN FUNCTIONS
HIGHER ORDER FUNCTIONS / HOFS EXAMPLE IN F#
HIGHER ORDER FUNCTIONS / BENEFITS
•Allows easy parallelism
•Encourages abstraction
•Reusing of common code
•Isolates the essential parts
•Allows easier unit testing
HIGHER ORDER FUNCTIONS
HIGHER ORDER FUNCTIONS/ HOFS IN JAVA
HIGHER ORDER FUNCTIONS / JAVA CLASSES
HIGHER ORDER FUNCTIONS / USAGE OF JAVA 8 FUNC. CLS.
HIGHER ORDER FUNCTIONS
HIGHER ORDER FUNCTIONS / LAMBDA EXPRESSIONS
• A lambda expression is an anonymous
method
• Lambdas favor HOFs
• more powerful libraries
• more expressive, more readable, less
error-prone use code
• Boosts developer productivity
• key to an accessible parallelism strategy
HIGHER ORDER FUNCTIONS / LAMBDA EXAMPLES 1
HIGHER ORDER FUNCTIONS / LAMBDA EXAMPLES 2
HIGHER ORDER FUNCTIONS / HOF IN JAVA 8
HIGHER ORDER FUNCTIONS
HIGHER ORDER FUNCTIONS / FUNC. INTERFACE EXAMPLE
HIGHER ORDER FUNCTIONS / FUNCTION REFERENCES
CHECKPOINT
FUNCTIONS
(PURE
FUNCTIONS)
A function is said to be pure if
1. it returns same set of values
for same set of inputs
2. It does not have any
observable side effects
PURE FUNCTIONS / DEFINITION
PURE FUNCTIONS / EXAMPLE 1
PURE FUNCTIONS / EXAMPLE 2
Impure functions / Side effects :
1. Alter parameters passed by ref
2. Alter members of passed
objects
3. Alter external objects
PURE FUNCTIONS / SIDE EFFECTS
PURE FUNCTIONS / EXAMPLE 2
• sin(x)
• length(a)
• random()
• println(String s)
• Insert values(x, y, z) into DB_TABLE
PURE FUNCTIONS / SAMPLE OF PURE AND IMPURE FNC
• easier to understand
• easy maintenance
• easy testing / unit-testing
• favor concurrency
PURE FUNCTIONS / PROS
PURE FUNCTIONS / BENEFITS
“No side effects” is utopic
PURE FUNCTIONS / CONS
FUNCTION
COMPOSITION
FUNCTION COMPOSITION / MATH
FUNCTION COMPOSITION / SUPPORT IN JAVA 8
FUNCTION COMPOSITION / THE POWER OF COMPOSITION
CHECKPOINT
NO LOOPS
NO LOOPS / RECURSION
NO LOOPS
(RECURSION)
RECURSION / EXAMPLE OF AN ITERATIVE FUNCTION
A recursive function is a
function that calls itself
during its execution
RECURSION / RECURSIVE VS. ITERATION
RECURSION / TAIL RECURSION
Tail recursion = a recursive function
calls itself as its last action
NO LOOPS / RECURSION - TAIL RECURSION
NO LOOPS / RECURSION - TAIL RECURSION OPTIMIZATION
NO LOOPS / RECURSION - RECURSION ENCOURAGED
NO LOOPS
(FUNCTION
CHAINING)
NO LOOPS / FUNCTION CHAINING
• Similar to unix pipes :
ps -ax | tee processes.txt | more
• Already used in java in fluent interfaces
• Eliminate the need for intermediate variables
NO LOOPS / FUNCTION CHAINING
persons.stream()
.filter(e -> e.getGender() == Person.Sex.MALE)
.forEach(e -> System.out.println(e.getName()));
for (Person p : persons) {
if (p.getGender() == Person.Sex.MALE) {
System.out.println(p.getName());
}
}
NO LOOPS / AGGREGATE OPERATIONS
• They use internal iteration
• They process elements from a stream
• They support behavior as parameters
NO LOOPS / FUNCTION CHAINING EXAMPLE
NO LOOPS / FUNCTION CHAINING
NO LOOPS / FUNCTION CHAINING
double average = persons.stream()
.filter(p -> p.getGender() == Person.Sex.MALE)
.mapToInt(Person::getAge)
.average()
.getAsDouble();
FUNCTION CHAINING / DEFAULT METHODS
FUNCTION CHAINING / DEFAULT METHODS
FUNCTIONS CHAINING / STREAMS IN JAVA 8
• Streams do not provide a means to directly access or
manipulate their elements
• are concerned with declaratively describing the
computational operations which will be performed in
aggregate on that source
• No storage: they carry values from a source through a
pipeline
• Functional in nature ( operations do not modify its
underlying data)
• Operations can be implemented lazily ( for single pass
execution & efficient implementation of short-circuit
operations)
• No bounds : streams can be infinite
FUNCTION CHAINING / STREAMS, OPTIONAL, LAZINESS
FUNCTION CHAINING / SEQUENTIAL REDUCE
FUNCTION CHAINING / SEQUENTIAL REDUCE
FUNCTION CHAINING / PARALLEL STREAMS
FUNCTION CHAINING / PARALLEL REDUCE
PERFORMANCE OF PARALLEL PROCESSING
FUNCTION CHAINING / OTHER EXAMPLES
OTHER
FUNCTIONAL
FEATURES
(OPTIONAL)
Shameless copy-paste from
www.oracle.com/technetwork/articles/java/java8-optional-2175753.html
OPTIONAL / WHY OPTIONAL ?
OPTIONAL / NULL, THE BILLION DOLLAR MISTAKE
"I call it my billion-dollar mistake. It was the invention of the
null reference in 1965. […]
I couldn't resist the temptation to put in a null reference,
simply because it was so easy to implement.
This has led to innumerable errors, vulnerabilities, and system
crashes, which have probably caused a billion dollars of pain
and damage in the last forty years“
Tony Hoare
OPTIONAL / THE SOLUTION TO NULL
java.util.Optional<T> :
• A class that encapsulates an optional value
• A single-value container that either contains
a value or doesn't (empty)
OPTIONAL / HOW TO CREATE IT
OPTIONAL / HOW TO USE IT
OPTIONAL / THE MOST IMPORTANT METHODS
OPTIONAL / RETURN TO ORIGINAL EXAMPLE
OPTIONAL / BENEFITS
• Idiot proof / Clear intent
• Cleaner code (no more null checks)
• Encourages method chaining
• End of NullPointerException
OPTIONAL / CONS
• Performance
• Serialization - Optional is not
• Certain operations involving
parametric polymorphism become
cumbersome
CHECKPOINT
FP CHANGES
EVERYTHING
EVERYTHING CHANGES / THREADS WITH LAMBDAS
EVERYTHING CHANGES / ACTION LISTENERS W/ LAMBDAS
EVERYTHING CHANGES / COMPARATORS
EVERYTHING CHANGES / LIST ITERATION, FILTERING, ETC.
EVERYTHING CHANGES / READING FILES
EVERYTHING CHANGES / SPRING
CHECKPOINT
• Immutability
• Higher Order Functions
• Pure functions
• No loops ( recursion, function chaining)
• Lazy evaluation
• Type inference
• Parallelism
• Easy coding / understanding
RECAP / FUNCTIONAL PROGRAMMING
• Introduced FP features
• Functional interfaces
• Function/Predicate/Producer/Consumer
• Default methods
• Lambda expressions
• Streams
• Map/Reduce/Filter/Collect
• Type inference
RECAP / JAVA 8
• Easier parallelization
• Less code
• Easy testing
• Results instead of steps
• Easy to understand code
WHAT IS FP ? / WHAT YOU GET ?
QUESTIONS
THE END
• Scheme, Lisp
• ML, OCaml
• Haskell
• Erlang
• Scala
• Clojure
• F#
WHAT’S NEXT ? / OTHER FUNCTIONAL LANGUAGES
•Retrolambda – backport of
java 8 lambdas in Java 7,6,5
•functionaljava.org
•Google Guava
WHAT’S NEXT ? / FP IN JAVA BEFORE JAVA8
•Reactive programming
WHAT’S NEXT ? / OTHER TECHNOLOGIES
WHAT’S/WHO’S
NEXT ?
Ad

More Related Content

What's hot (20)

Java 8 features
Java 8 featuresJava 8 features
Java 8 features
Oleg Tsal-Tsalko
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
Rohit Verma
 
Code generating beans in Java
Code generating beans in JavaCode generating beans in Java
Code generating beans in Java
Stephen Colebourne
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
Stratio
 
10 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 810 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 8
Garth Gilmour
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
Buddhini Seneviratne
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 Exams
Ganesh Samarthyam
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
Hari kiran G
 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
Tobias Coetzee
 
Lambdas
LambdasLambdas
Lambdas
malliksunkara
 
Xtend - better java with -less- noise
Xtend - better java with -less- noiseXtend - better java with -less- noise
Xtend - better java with -less- noise
Neeraj Bhusare
 
Refactoring to Java 8 (Devoxx UK)
Refactoring to Java 8 (Devoxx UK)Refactoring to Java 8 (Devoxx UK)
Refactoring to Java 8 (Devoxx UK)
Trisha Gee
 
Java SE 8 library design
Java SE 8 library designJava SE 8 library design
Java SE 8 library design
Stephen Colebourne
 
Java 8 best practices - Stephen Colebourne
Java 8 best practices - Stephen ColebourneJava 8 best practices - Stephen Colebourne
Java 8 best practices - Stephen Colebourne
JAXLondon_Conference
 
Functional programming with Xtend
Functional programming with XtendFunctional programming with Xtend
Functional programming with Xtend
Sven Efftinge
 
Lambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian GoetzLambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian Goetz
JAX London
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
Stephen Colebourne
 
Functional programming for the Advanced Beginner
Functional programming for the Advanced BeginnerFunctional programming for the Advanced Beginner
Functional programming for the Advanced Beginner
Luis Atencio
 
Java 8 - A step closer to Parallelism
Java 8 - A step closer to ParallelismJava 8 - A step closer to Parallelism
Java 8 - A step closer to Parallelism
jbugkorea
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slides
luqman bawany
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
Rohit Verma
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
Stratio
 
10 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 810 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 8
Garth Gilmour
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 Exams
Ganesh Samarthyam
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
Hari kiran G
 
Xtend - better java with -less- noise
Xtend - better java with -less- noiseXtend - better java with -less- noise
Xtend - better java with -less- noise
Neeraj Bhusare
 
Refactoring to Java 8 (Devoxx UK)
Refactoring to Java 8 (Devoxx UK)Refactoring to Java 8 (Devoxx UK)
Refactoring to Java 8 (Devoxx UK)
Trisha Gee
 
Java 8 best practices - Stephen Colebourne
Java 8 best practices - Stephen ColebourneJava 8 best practices - Stephen Colebourne
Java 8 best practices - Stephen Colebourne
JAXLondon_Conference
 
Functional programming with Xtend
Functional programming with XtendFunctional programming with Xtend
Functional programming with Xtend
Sven Efftinge
 
Lambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian GoetzLambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian Goetz
JAX London
 
Functional programming for the Advanced Beginner
Functional programming for the Advanced BeginnerFunctional programming for the Advanced Beginner
Functional programming for the Advanced Beginner
Luis Atencio
 
Java 8 - A step closer to Parallelism
Java 8 - A step closer to ParallelismJava 8 - A step closer to Parallelism
Java 8 - A step closer to Parallelism
jbugkorea
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slides
luqman bawany
 

Viewers also liked (20)

Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
Andrea Iacono
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming Fundamentals
Shahriar Hyder
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Veerabadra Badra
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
Scott Wlaschin
 
Features of java
Features of javaFeatures of java
Features of java
Hitesh Kumar
 
Functional Programming in JAVA 8
Functional Programming in JAVA 8Functional Programming in JAVA 8
Functional Programming in JAVA 8
Ignasi Marimon-Clos i Sunyol
 
Principles of Object Oriented Programming
Principles of Object Oriented ProgrammingPrinciples of Object Oriented Programming
Principles of Object Oriented Programming
Kasun Ranga Wijeweera
 
Features of java
Features of javaFeatures of java
Features of java
WILLFREDJOSE W
 
Java features
Java featuresJava features
Java features
myrajendra
 
Uses of Cupcakes For Any Occasion in Hyderabad!
 Uses of Cupcakes For Any Occasion in Hyderabad! Uses of Cupcakes For Any Occasion in Hyderabad!
Uses of Cupcakes For Any Occasion in Hyderabad!
bookthecake.com
 
Csc1100 lecture01 ch01 pt2-paradigm
Csc1100 lecture01 ch01 pt2-paradigmCsc1100 lecture01 ch01 pt2-paradigm
Csc1100 lecture01 ch01 pt2-paradigm
IIUM
 
Core FP Concepts
Core FP ConceptsCore FP Concepts
Core FP Concepts
Diego Pacheco
 
Oop project briefing sem 1 2015 2016
Oop project briefing  sem 1 2015 2016Oop project briefing  sem 1 2015 2016
Oop project briefing sem 1 2015 2016
IIUM
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...
Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...
Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...
yaminohime
 
Good Programming Practice
Good Programming PracticeGood Programming Practice
Good Programming Practice
Bikalpa Gyawali
 
Ada 95 - Structured programming
Ada 95 - Structured programmingAda 95 - Structured programming
Ada 95 - Structured programming
Gneuromante canalada.org
 
Functional Programming in Java - Code for Maintainability
Functional Programming in Java - Code for MaintainabilityFunctional Programming in Java - Code for Maintainability
Functional Programming in Java - Code for Maintainability
Marcin Stepien
 
Why C is Called Structured Programming Language
Why C is Called Structured Programming LanguageWhy C is Called Structured Programming Language
Why C is Called Structured Programming Language
Sinbad Konick
 
Programming languages
Programming languagesProgramming languages
Programming languages
Eelco Visser
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
Andrea Iacono
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming Fundamentals
Shahriar Hyder
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
Scott Wlaschin
 
Principles of Object Oriented Programming
Principles of Object Oriented ProgrammingPrinciples of Object Oriented Programming
Principles of Object Oriented Programming
Kasun Ranga Wijeweera
 
Uses of Cupcakes For Any Occasion in Hyderabad!
 Uses of Cupcakes For Any Occasion in Hyderabad! Uses of Cupcakes For Any Occasion in Hyderabad!
Uses of Cupcakes For Any Occasion in Hyderabad!
bookthecake.com
 
Csc1100 lecture01 ch01 pt2-paradigm
Csc1100 lecture01 ch01 pt2-paradigmCsc1100 lecture01 ch01 pt2-paradigm
Csc1100 lecture01 ch01 pt2-paradigm
IIUM
 
Oop project briefing sem 1 2015 2016
Oop project briefing  sem 1 2015 2016Oop project briefing  sem 1 2015 2016
Oop project briefing sem 1 2015 2016
IIUM
 
Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...
Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...
Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...
yaminohime
 
Good Programming Practice
Good Programming PracticeGood Programming Practice
Good Programming Practice
Bikalpa Gyawali
 
Functional Programming in Java - Code for Maintainability
Functional Programming in Java - Code for MaintainabilityFunctional Programming in Java - Code for Maintainability
Functional Programming in Java - Code for Maintainability
Marcin Stepien
 
Why C is Called Structured Programming Language
Why C is Called Structured Programming LanguageWhy C is Called Structured Programming Language
Why C is Called Structured Programming Language
Sinbad Konick
 
Programming languages
Programming languagesProgramming languages
Programming languages
Eelco Visser
 
Ad

Similar to Functional programming principles and Java 8 (20)

Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)
Calvin Cheng
 
Functional programming
Functional programmingFunctional programming
Functional programming
PiumiPerera7
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
Heartin Jacob
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
Edward D. Weinberger
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
Edward D. Weinberger
 
Writing Well Abstracted Automation on Foundations of Jello
Writing Well Abstracted Automation on Foundations of JelloWriting Well Abstracted Automation on Foundations of Jello
Writing Well Abstracted Automation on Foundations of Jello
Dan Cuellar
 
Refactoring
RefactoringRefactoring
Refactoring
AngelLuisBlasco
 
Functional programming is the most extreme programming
Functional programming is the most extreme programmingFunctional programming is the most extreme programming
Functional programming is the most extreme programming
samthemonad
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Dave Fancher
 
Functions and procedures
Functions and proceduresFunctions and procedures
Functions and procedures
underwan
 
TDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleTDD and the Legacy Code Black Hole
TDD and the Legacy Code Black Hole
Noam Kfir
 
Java+8-New+Features.pdf
Java+8-New+Features.pdfJava+8-New+Features.pdf
Java+8-New+Features.pdf
gurukanth4
 
Intro to java 8
Intro to java 8Intro to java 8
Intro to java 8
John Godoi
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
Leninkumar Koppoju
 
Functional JavaScript Fundamentals
Functional JavaScript FundamentalsFunctional JavaScript Fundamentals
Functional JavaScript Fundamentals
Srdjan Strbanovic
 
Complete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itComplete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept it
lokeshpappaka10
 
JAVA 8 Parallel Stream
JAVA 8 Parallel StreamJAVA 8 Parallel Stream
JAVA 8 Parallel Stream
Tengwen Wang
 
Java8
Java8Java8
Java8
Felipe Mamud
 
Functional-style control flow in F#
Functional-style control flow in F#Functional-style control flow in F#
Functional-style control flow in F#
LincolnAtkinson
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
Riccardo Terrell
 
Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)
Calvin Cheng
 
Functional programming
Functional programmingFunctional programming
Functional programming
PiumiPerera7
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
Heartin Jacob
 
Writing Well Abstracted Automation on Foundations of Jello
Writing Well Abstracted Automation on Foundations of JelloWriting Well Abstracted Automation on Foundations of Jello
Writing Well Abstracted Automation on Foundations of Jello
Dan Cuellar
 
Functional programming is the most extreme programming
Functional programming is the most extreme programmingFunctional programming is the most extreme programming
Functional programming is the most extreme programming
samthemonad
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Dave Fancher
 
Functions and procedures
Functions and proceduresFunctions and procedures
Functions and procedures
underwan
 
TDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleTDD and the Legacy Code Black Hole
TDD and the Legacy Code Black Hole
Noam Kfir
 
Java+8-New+Features.pdf
Java+8-New+Features.pdfJava+8-New+Features.pdf
Java+8-New+Features.pdf
gurukanth4
 
Intro to java 8
Intro to java 8Intro to java 8
Intro to java 8
John Godoi
 
Functional JavaScript Fundamentals
Functional JavaScript FundamentalsFunctional JavaScript Fundamentals
Functional JavaScript Fundamentals
Srdjan Strbanovic
 
Complete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itComplete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept it
lokeshpappaka10
 
JAVA 8 Parallel Stream
JAVA 8 Parallel StreamJAVA 8 Parallel Stream
JAVA 8 Parallel Stream
Tengwen Wang
 
Functional-style control flow in F#
Functional-style control flow in F#Functional-style control flow in F#
Functional-style control flow in F#
LincolnAtkinson
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
Riccardo Terrell
 
Ad

Recently uploaded (20)

Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
Microsoft Excel Core Points Training.pptx
Microsoft Excel Core Points Training.pptxMicrosoft Excel Core Points Training.pptx
Microsoft Excel Core Points Training.pptx
Mekonnen
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
PRTG Network Monitor Crack Latest Version & Serial Key 2025 [100% Working]
PRTG Network Monitor Crack Latest Version & Serial Key 2025 [100% Working]PRTG Network Monitor Crack Latest Version & Serial Key 2025 [100% Working]
PRTG Network Monitor Crack Latest Version & Serial Key 2025 [100% Working]
saimabibi60507
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Creating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdfCreating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdf
Applitools
 
DVDFab Crack FREE Download Latest Version 2025
DVDFab Crack FREE Download Latest Version 2025DVDFab Crack FREE Download Latest Version 2025
DVDFab Crack FREE Download Latest Version 2025
younisnoman75
 
Tools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google CertificateTools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
Innovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at allInnovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at all
ayeshakanwal75
 
Full Cracked Resolume Arena Latest Version
Full Cracked Resolume Arena Latest VersionFull Cracked Resolume Arena Latest Version
Full Cracked Resolume Arena Latest Version
jonesmichealj2
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
Microsoft Excel Core Points Training.pptx
Microsoft Excel Core Points Training.pptxMicrosoft Excel Core Points Training.pptx
Microsoft Excel Core Points Training.pptx
Mekonnen
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
PRTG Network Monitor Crack Latest Version & Serial Key 2025 [100% Working]
PRTG Network Monitor Crack Latest Version & Serial Key 2025 [100% Working]PRTG Network Monitor Crack Latest Version & Serial Key 2025 [100% Working]
PRTG Network Monitor Crack Latest Version & Serial Key 2025 [100% Working]
saimabibi60507
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Creating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdfCreating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdf
Applitools
 
DVDFab Crack FREE Download Latest Version 2025
DVDFab Crack FREE Download Latest Version 2025DVDFab Crack FREE Download Latest Version 2025
DVDFab Crack FREE Download Latest Version 2025
younisnoman75
 
Tools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google CertificateTools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
Innovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at allInnovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at all
ayeshakanwal75
 
Full Cracked Resolume Arena Latest Version
Full Cracked Resolume Arena Latest VersionFull Cracked Resolume Arena Latest Version
Full Cracked Resolume Arena Latest Version
jonesmichealj2
 

Functional programming principles and Java 8

Editor's Notes

  • #2: Ce ne propunem ? Prezentarea este destul de ambitioasa pentru ca ataca doua tinte: functional programming si java8 most important features. Focusul va fi pe FP. Disclaimer: - codul in F#
  • #4: The evolution of the clock speed over time. Unul din factorii care contribuiau la imbunatatirea puterii de calcul si-a oprit cresterea. Este prima data cand legea lui Moore este pusa sub semnul intrebarii.
  • #5: Hardware-ul se schimba -> software-ul tre’ sa se schimbe pentru a tine pasul. Articol: The free lunch is over : - processor manufacturers will focus on products that better support multithreading (such as multi-core processors) - software developers will be forced to develop massively multithreaded programs as a way to better use such processors (i.e: proasta calitate a codului, nu mai poate fi acoperita de imbunatatirea vitezei de calcul) Codul nostru va rula distribuit intre core-urile procesorului.
  • #6: Evolutia limbajelor de programare. A se nota faptul ca limbajele functionale au aparut cu mult inaintea limbajelor OOP. Principiile din limbajele functionale se mapeaza mult mai bine pe ideea de multi threading / paralelism.
  • #9: Principiile FP derivate din cele doua concepte prezentate anterior
  • #10: Easier parallelization != No work for parallelization Results instead of steps -> SQL Verbe in locul substantivelor
  • #14: Imutabilitatea nu e ceva nou. Este recomandata si-n OOP.
  • #15: No setters Final fields Final class Java examples ?
  • #16: Un exemplu mai complex. Unul din campurile clasei este mutabil. Ultima metoda returneaza o copie defensiva pentru a evita mutabilitatea.
  • #17: Exemplu de clasa imutabila in Scala.
  • #18: Exemplu de clasa imutabila in F#. Pentru a face un obiect mutabil trebuie utilizat cuvantul cheie “mutable”
  • #19: Talk about the memory consumption and the extra work to be done by the garbage collector. Extrapolate the example above to lists, trees, etc.
  • #21: Other benefits: - don't need a copy constructor - don't need an implementation of clone - allow hashCode to use lazy initialization, and to cache its return value - don't need to be copied defensively when used as a field - make good Map keys and Set elements (these objects must not change state while in the collection) - always have "failure atomicity" : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state
  • #22: In loc de obiectul rational de mai devreme sa ne gandim ca avem o lista.add Garbage collection: ok atata timp cat nu lucrezi la Twitter.
  • #25: This cannot be achieved in Java but … talk about the new functional interfaces ; Predicate, Filter, …
  • #26: HOFs can be assigned to variables HOFs can be created at runtime and used Functions are just as any other data types
  • #27: Sum accepts another function as input parameter
  • #28: higherOrderFunction returns a function as a result
  • #29: Functions as first class citizens Functions as parameters Functions as return values
  • #30: sumOfSquares -> easy abstraction –> sum (f) Easy parallelism
  • #32: A new package added in java8 In java everything is a class -> functions are classes
  • #33: The most important java classes in the java.util.function package All introduced in Java8
  • #34: Cam asa am fi utilizat clasele in Java 7
  • #35: Note the lambda expression No boilerplate Explain the type inference
  • #36: Remember the anonymous classes in java
  • #37: Examples with the most important classes implemented as lambda expressions
  • #40: Cum acoperim toate situatiile ? Prin annotation : FunctionalInterface A functional interface has only one abstract method. Instances of functional interfaces can be created with lambda or method references
  • #41: This is how we use the Functional Interface annotation. Note: the lambda expression used to define an anonymous definition of a Functional Interface
  • #42: Cum utilizam metodele deja existente ? De observat referintele la metodele din clasele Math, Integer.
  • #43: HOF Lambda Function references
  • #44: Pure functions = No side effects
  • #46: Impure function - has side effects
  • #47: Impure function -> it doesn’t return the same values for the same inputs
  • #50: Sin = pure Length = pure Random() = impure Println() = impure SQL Insert = impure
  • #51: Easier to maintain: devs spend less time analyzing the impact Once tested all edge conditions we can be sure that the function behaves correctly Easy concurency: see next side/example
  • #52: No side effects favorizeaza paralelismul The same input -> same output favorizeaza testarea si intelegerea
  • #53: Any write to the console is a side-effect. Database updates or file writes on disk is a side-effect. So we cannot be 100% pure but the goal is to be as pure as possible. In an input – process– output flow the goal is to keep the middle (process) functional.
  • #55: g o f (c) = #
  • #56: Metodele compose si andThen
  • #58: Pure functions Function composition HOF Lambdas Function references
  • #60: What is the problem ? Incurajeaza shared state (variabilele partajate) = nu bine pt. paralelism Mult boilerplate
  • #61: Why avoid loops ? boilerplate code Incurajeaza partajarea state-ului deci nu este prietenos cu multi-threadingul.
  • #63: In some cases ( most of them ? ) recursion is more intuitive then iteration. Functional languages have better implementations for recursion For OOP languages iteration is much faster than recursion The mantra of functional languages: CLARITY TRUMPS EFFICIENCY (preferam claritatea vs. eficienta)
  • #64: the function’s stack frame can be reused. Remember stiva de executie a unei functii.
  • #65: After the call to factorial(n-1) there is still work to be done => not a tail recursive action
  • #66: Note: Since the stack trace is optimized, when printing the stack trace one will only see the last call instead of the entire stack trace.
  • #67: Functional languages have better support for recursion (see the list.head, list.tail) This is not possible with all lists in idiomatic java.
  • #68: Function chaining = Un caz particular de compozitie
  • #69: To be discussed here: Imperative approach vs. Functional approach : For vs. map-reduce State vs. stateless
  • #70: Discussion about state / share state ( in a multi-threaded env.) : let’s sum the salaries of males in a multi-threaded env. Func. Chaining can be seen as a particular case of composition.
  • #71: Discussion about state / share state ( in a multi-threaded env.) : let’s sum the salaries of males in a multi-threaded env. Func. Chaining can be seen as a particular case of composition.
  • #72: Note the chaining of combinator methods : map, filter, reduce/foldLeft
  • #73: The same functionality in Java8. Imperative vs. Declarative style / Ce face functia vs. Cum face functia / The SQL Example. Note 1: the stream() method Note 2: a method added to a the list interface (DEFAULT METHODS discussion) Discussion about map/filter/reduce We’ll come back to map/reduce/filter in a few moments
  • #74: The average age of males in the persons list. When using streams we need the following components: 1 A source ( list ) 2.Zero or more intermediate operations ( filters, transformers) 3. A terminal operation ( average)
  • #75: Default Method Discussion 2. Stream interface
  • #76: The Stream interface and the map / reduce methods
  • #77: Streams cannot be reused. Please check the Stream javadoc . http://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps
  • #78: The stream could have been infinite I could have used only lambdas Note the findFirst method returning an optional (discussed later in this material) Re-start the map/reduce discussion
  • #79: Reduce needs to be associative (a+b)+c = a+(b+c), i.e. the order in which the additions are performed doesn't matter.
  • #80: How sequential reduce works.
  • #81: Free parallelism but this doesn’t happen every time Sum() is a particular form of reduce() – a shortcut for reduce(0, (a,b) -> a+b) reduce, collect, sum = terminal methods Note: Order of filtering matters
  • #82: Note: the operation has to be associative otherwise the result will not be consistent (no compilation or runtime error) Example of a non associative operation: x*x + y*y Discussion about non-associative
  • #83: Disclaimer: the table shows the test results in ideal conditions ( no other threads were running) - in production systems you won’t get this kind of difference
  • #84: The power of collectors
  • #87: The problem with null: Depending on the context, null means “no value”, other times it means “error” or “nothing”, but it can even mean “success”
  • #88: Optional is inspired from Haskel and Scala
  • #93: Idiot proof : It forces you to actively think about the absent case if you want your program to compile There are three ways to deal with the absence of a value in an Optional: to provide a substitute value, to call a function to provide a substitute value, or to throw an exception
  • #95: Functional programming = no loops Recursivitate Function chaining Function composition Streams Map / reduce Default methods Optional
  • #96: Functional programming = no loops Recursivitate Function chaining ( this is also related to composition) Streams Map / reduce
  • #97: Lambda instead of a Runnable Runnable este o interfata functionala
  • #98: Lambda instead of an Action Listener
  • #99: Lambda instead of a Comparator. Why the Users type has been specified ? - where is the type inference ?
  • #100: Method reference in a forEach method
  • #101: BufferedReader.lines() returns a Stream Files.lines() returns a Stream as well. The examples shows how to use the stream in a try-with-resources ( it implements AutoClosable).
  • #102: Spring jdbc template with lambda expressions ( instead of RowMapper.mapRow(ResultSet, int rowNum)
  • #104: Outside the scope : Advanced Laziness Monads Function currying
  • #105: Outside the scope : Java8 ------------------------------------ Type Annotations Date and time API Lambda translation to bytecode Nashorn Javascript engine
  • #106: Easier parallelization != No work for parallelization What instead of How Verbe in loc de substantive
  • #108: Some non-programming mistakes have been intentionally inserted into the presentation
  • #111: Responsive: The system responds in a timely manner Resilient: The system stays responsive even in failure Elastic: The service allocates resources as needed ( according to the workload) Message Driven: Async message passing for loose coupling, isolation, transparency