SlideShare una empresa de Scribd logo
1 de 111
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 ?

Más contenido relacionado

La actualidad más candente

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 scalaStratio
 
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 8Garth 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 ExamsGanesh 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 CardHari kiran G
 
Xtend - better java with -less- noise
Xtend - better java with -less- noiseXtend - better java with -less- noise
Xtend - better java with -less- noiseNeeraj 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 ColebourneJAXLondon_Conference
 
Functional programming with Xtend
Functional programming with XtendFunctional programming with Xtend
Functional programming with XtendSven 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 GoetzJAX London
 
Functional programming for the Advanced Beginner
Functional programming for the Advanced BeginnerFunctional programming for the Advanced Beginner
Functional programming for the Advanced BeginnerLuis 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 Parallelismjbugkorea
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slidesluqman bawany
 

La actualidad más candente (20)

Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Code generating beans in Java
Code generating beans in JavaCode generating beans in Java
Code generating beans in Java
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
 
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
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
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
 
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
 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
 
Lambdas
LambdasLambdas
Lambdas
 
Xtend - better java with -less- noise
Xtend - better java with -less- noiseXtend - better java with -less- noise
Xtend - better java with -less- noise
 
Refactoring to Java 8 (Devoxx UK)
Refactoring to Java 8 (Devoxx UK)Refactoring to Java 8 (Devoxx UK)
Refactoring to Java 8 (Devoxx UK)
 
Java SE 8 library design
Java SE 8 library designJava SE 8 library design
Java SE 8 library design
 
Java 8 best practices - Stephen Colebourne
Java 8 best practices - Stephen ColebourneJava 8 best practices - Stephen Colebourne
Java 8 best practices - Stephen Colebourne
 
Functional programming with Xtend
Functional programming with XtendFunctional programming with Xtend
Functional programming with Xtend
 
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
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 
Functional programming for the Advanced Beginner
Functional programming for the Advanced BeginnerFunctional programming for the Advanced Beginner
Functional programming for the Advanced Beginner
 
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
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slides
 

Destacado

Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday lifeAndrea Iacono
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming FundamentalsShahriar 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 ProgrammingKasun 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-paradigmIIUM
 
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 2016IIUM
 
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 PracticeBikalpa 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 MaintainabilityMarcin 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 LanguageSinbad Konick
 
Programming languages
Programming languagesProgramming languages
Programming languagesEelco Visser
 

Destacado (20)

Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming Fundamentals
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
Features of java
Features of javaFeatures of java
Features of java
 
Functional Programming in JAVA 8
Functional Programming in JAVA 8Functional Programming in JAVA 8
Functional Programming in JAVA 8
 
Principles of Object Oriented Programming
Principles of Object Oriented ProgrammingPrinciples of Object Oriented Programming
Principles of Object Oriented Programming
 
Features of java
Features of javaFeatures of java
Features of java
 
Java features
Java featuresJava features
Java features
 
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!
 
Csc1100 lecture01 ch01 pt2-paradigm
Csc1100 lecture01 ch01 pt2-paradigmCsc1100 lecture01 ch01 pt2-paradigm
Csc1100 lecture01 ch01 pt2-paradigm
 
Core FP Concepts
Core FP ConceptsCore FP Concepts
Core FP Concepts
 
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
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
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...
 
Good Programming Practice
Good Programming PracticeGood Programming Practice
Good Programming Practice
 
Ada 95 - Structured programming
Ada 95 - Structured programmingAda 95 - Structured programming
Ada 95 - Structured programming
 
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
 
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
 
Programming languages
Programming languagesProgramming languages
Programming languages
 

Similar a Functional programming principles and Java 8

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 programmingPiumiPerera7
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin 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 JelloDan 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 programmingsamthemonad
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional ProgrammingDave Fancher
 
Functions and procedures
Functions and proceduresFunctions and procedures
Functions and proceduresunderwan
 
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 HoleNoam Kfir
 
Java+8-New+Features.pdf
Java+8-New+Features.pdfJava+8-New+Features.pdf
Java+8-New+Features.pdfgurukanth4
 
Intro to java 8
Intro to java 8Intro to java 8
Intro to java 8John Godoi
 
Functional JavaScript Fundamentals
Functional JavaScript FundamentalsFunctional JavaScript Fundamentals
Functional JavaScript FundamentalsSrdjan 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 itlokeshpappaka10
 
JAVA 8 Parallel Stream
JAVA 8 Parallel StreamJAVA 8 Parallel Stream
JAVA 8 Parallel StreamTengwen 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
 

Similar a 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)
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
 
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
 
Refactoring
RefactoringRefactoring
Refactoring
 
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
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
Functions and procedures
Functions and proceduresFunctions and procedures
Functions and procedures
 
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
 
Java+8-New+Features.pdf
Java+8-New+Features.pdfJava+8-New+Features.pdf
Java+8-New+Features.pdf
 
Intro to java 8
Intro to java 8Intro to java 8
Intro to java 8
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
 
Functional JavaScript Fundamentals
Functional JavaScript FundamentalsFunctional JavaScript Fundamentals
Functional JavaScript Fundamentals
 
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
 
JAVA 8 Parallel Stream
JAVA 8 Parallel StreamJAVA 8 Parallel Stream
JAVA 8 Parallel Stream
 
Java8
Java8Java8
Java8
 
Functional-style control flow in F#
Functional-style control flow in F#Functional-style control flow in F#
Functional-style control flow in F#
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
 

Último

Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 

Último (20)

Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 

Functional programming principles and Java 8

Notas del editor

  1. 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#
  2. 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.
  3. 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.
  4. 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.
  5. Principiile FP derivate din cele doua concepte prezentate anterior
  6. Easier parallelization != No work for parallelization Results instead of steps -> SQL Verbe in locul substantivelor
  7. Imutabilitatea nu e ceva nou. Este recomandata si-n OOP.
  8. No setters Final fields Final class Java examples ?
  9. Un exemplu mai complex. Unul din campurile clasei este mutabil. Ultima metoda returneaza o copie defensiva pentru a evita mutabilitatea.
  10. Exemplu de clasa imutabila in Scala.
  11. Exemplu de clasa imutabila in F#. Pentru a face un obiect mutabil trebuie utilizat cuvantul cheie “mutable”
  12. Talk about the memory consumption and the extra work to be done by the garbage collector. Extrapolate the example above to lists, trees, etc.
  13. 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
  14. 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.
  15. This cannot be achieved in Java but … talk about the new functional interfaces ; Predicate, Filter, …
  16. HOFs can be assigned to variables HOFs can be created at runtime and used Functions are just as any other data types
  17. Sum accepts another function as input parameter
  18. higherOrderFunction returns a function as a result
  19. Functions as first class citizens Functions as parameters Functions as return values
  20. sumOfSquares -> easy abstraction –> sum (f) Easy parallelism
  21. A new package added in java8 In java everything is a class -> functions are classes
  22. The most important java classes in the java.util.function package All introduced in Java8
  23. Cam asa am fi utilizat clasele in Java 7
  24. Note the lambda expression No boilerplate Explain the type inference
  25. Remember the anonymous classes in java
  26. Examples with the most important classes implemented as lambda expressions
  27. 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
  28. This is how we use the Functional Interface annotation. Note: the lambda expression used to define an anonymous definition of a Functional Interface
  29. Cum utilizam metodele deja existente ? De observat referintele la metodele din clasele Math, Integer.
  30. HOF Lambda Function references
  31. Pure functions = No side effects
  32. Impure function - has side effects
  33. Impure function -> it doesn’t return the same values for the same inputs
  34. Sin = pure Length = pure Random() = impure Println() = impure SQL Insert = impure
  35. 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
  36. No side effects favorizeaza paralelismul The same input -> same output favorizeaza testarea si intelegerea
  37. 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.
  38. g o f (c) = #
  39. Metodele compose si andThen
  40. Pure functions Function composition HOF Lambdas Function references
  41. What is the problem ? Incurajeaza shared state (variabilele partajate) = nu bine pt. paralelism Mult boilerplate
  42. Why avoid loops ? boilerplate code Incurajeaza partajarea state-ului deci nu este prietenos cu multi-threadingul.
  43. 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)
  44. the function’s stack frame can be reused. Remember stiva de executie a unei functii.
  45. After the call to factorial(n-1) there is still work to be done => not a tail recursive action
  46. 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.
  47. Functional languages have better support for recursion (see the list.head, list.tail) This is not possible with all lists in idiomatic java.
  48. Function chaining = Un caz particular de compozitie
  49. To be discussed here: Imperative approach vs. Functional approach : For vs. map-reduce State vs. stateless
  50. 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.
  51. 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.
  52. Note the chaining of combinator methods : map, filter, reduce/foldLeft
  53. 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
  54. 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)
  55. Default Method Discussion 2. Stream interface
  56. The Stream interface and the map / reduce methods
  57. Streams cannot be reused. Please check the Stream javadoc . http://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps
  58. 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
  59. Reduce needs to be associative (a+b)+c = a+(b+c), i.e. the order in which the additions are performed doesn't matter.
  60. How sequential reduce works.
  61. 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
  62. 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
  63. 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
  64. The power of collectors
  65. 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”
  66. Optional is inspired from Haskel and Scala
  67. 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
  68. Functional programming = no loops Recursivitate Function chaining Function composition Streams Map / reduce Default methods Optional
  69. Functional programming = no loops Recursivitate Function chaining ( this is also related to composition) Streams Map / reduce
  70. Lambda instead of a Runnable Runnable este o interfata functionala
  71. Lambda instead of an Action Listener
  72. Lambda instead of a Comparator. Why the Users type has been specified ? - where is the type inference ?
  73. Method reference in a forEach method
  74. 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).
  75. Spring jdbc template with lambda expressions ( instead of RowMapper.mapRow(ResultSet, int rowNum)
  76. Outside the scope : Advanced Laziness Monads Function currying
  77. Outside the scope : Java8 ------------------------------------ Type Annotations Date and time API Lambda translation to bytecode Nashorn Javascript engine
  78. Easier parallelization != No work for parallelization What instead of How Verbe in loc de substantive
  79. Some non-programming mistakes have been intentionally inserted into the presentation
  80. 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