Functional programming principles and Java 8

111
FUNCTIONAL PRINCIPLES Introduction to Functional Programming and Java 8

Transcript of Functional programming principles and Java 8

FUNCTIONAL

PRINCIPLES

Introduction to Functional Programming and Java 8

WHY ?

WHY FUNCTIONAL PROGRAMMING ? / MOORE’S LAW

WHY FUNCTIONAL PROGRAMMING ? / MULTI CORE TREND

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 / JAVA CLASSES

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 / LAMBDA EXAMPLES 1

HIGHER ORDER FUNCTIONS / LAMBDA EXAMPLES 2

HIGHER ORDER FUNCTIONS / HOF IN JAVA 8

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

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

CHECKPOINT

NO LOOPS

NO LOOPS

(RECURSION)

RECURSION / EXAMPLE OF AN ITERATIVE FUNCTION

A recursive function is a function that calls itself during its execution

RECURSION / TAIL RECURSION

Tail recursion = a recursive function calls itself as its last action

NO LOOPS / RECURSION - TAIL RECURSION

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();

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 REDUCE

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 ?