Upload
dragos-balan
View
81
Download
3
Embed Size (px)
Citation preview
WHY FUNCTIONAL PROGRAMMING ? / SOME HISTORY
•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 ?
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
•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
HOF = functions that can take other functions as arguments and / or return other functions as result
HIGHER ORDER FUNCTIONS / DEFINITION
•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 / USAGE OF JAVA 8 FUNC. CLS.
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
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 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
• 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
FUNCTION COMPOSITION / MATH
FUNCTION COMPOSITION / SUPPORT IN JAVA 8
FUNCTION COMPOSITION / THE POWER OF COMPOSITION
RECURSION / EXAMPLE OF AN ITERATIVE FUNCTION
A recursive function is a function that calls itself during its execution
RECURSION / RECURSIVE VS. ITERATION
NO LOOPS / RECURSION - TAIL RECURSION OPTIMIZATION
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
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 / PARALLEL STREAMS
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 / 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 / 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
• 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 ?
• 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