9. A programming paradigm that ...
● Treats function as primitive
● Avoids state and mutable data
● Is declarative
Definition of Functional Programming
10. To be a function
function succ(int y){
return y++;
}
Definition
11. int x = 1;
function dummy(int y){
x++;
return x+y;
}
Not to be a function
Definition
12. int x = 1;
function dummy(int y){
x++;
return x+y;
}
Not to be a function
Definition
13. Functions as First-Class Citizens
- High-Order Functions
- Lambda
- Top-Level Functions
Immutable data
(Hadi Hariri Devoxx France 2015)
Functional Language
16. “Software product is embedded in a cultural matrix of
applications, users, laws, and machines vehicles.
These all change continually, and their changes inexorably
force change upon the software product.”
Frederic brooks
The context
17. Every 18 months a CPU's transistors will
shrink in size by a factor of two.
Moor Law
The context
18. - In 2002, limitations in a CPU's circuitry.
- The multi-core processor was born.
Moor Law (New Context)
The context
20. “Reduce the gap between the serial and parallel
versions of the same computation”
Brian Goetz (Lambda project leader)
The context
21. public List<Output> processInputs(List<Input> inputs)
throws InterruptedException, ExecutionException {
int threads = Runtime.getRuntime().availableProcessors();
ExecutorService service = Executors.newFixedThreadPool(threads);
List<Future<Output>> futures = new ArrayList<Future<Output>>();
for (final Input input : inputs) {
Callable<Output> callable = new Callable<Output>() {
public Output call() throws Exception {
Output output = new Output();
// process your input here and compute the output
return output;
}
};
futures.add(service.submit(callable));
}
service.shutdown();
List<Output> outputs = new ArrayList<Output>();
for (Future<Output> future : futures) {
outputs.add(future.get());
}
return outputs;
}
Pallelizing with OOP
The context
22. Output out = input.process(treatment);
Output out = Input.processInParallel(treatment);
Pallelizing with FP
The context
23. => Lambda expression
=> Functional Interface
=> Optional API
=> Stream API
….
Java 8 main new features
29. Provide target types for lambda expressions ...
Has a single abstract method, ..., to which the
lambda expression's parameter and return types are
matched or adapted.
Functional Interface
30. int x -> x * 2;
public interface IntOperation {
int operate(int i);
}
Functional Interface
32. Functions accept one argument and produce a result.
@FunctionalInterface
Interface Function<T,R>{
R apply(T t);
}
Functional Interface
Function
33. // String to an integer
Function<String, Integer> stringToInt = x -> Integer.valueOf(x);
int toto = stringToInt(“10”);
Functional Interface
Function
34. Suppliers produce a result of a given generic type.
Unlike Functions, Suppliers don't accept arguments.
@FunctionalInterface
Interface Supplier<T>{
T get()
}
Functional Interface
Supplier
36. Consumers represents operations to be performed on a single
input argument.
@FunctionalInterface
public interface Consumer<T>{
void accept(T t)
}
Functional Interface
Consumer
41. What is the type of [x -> 2 * x] ?
public interface IntOperation {
int operate(int i);
}
public interface DoubleOperation {
double operate(double i);
}
Type Inference
Type Inference
42. Java does have type inferencing when using generics.
public <T> T foo(T t) {
return t;
}
Type Inference
Type Inference
43. ● DoubleOperation doubleOp = x -> x * 2;
● IntOperation intOp = x -> x * 2;
Inference by declaration
Type Inference
44. ● DoubleOperation doubleOp ;
doubleOp = x -> x * 2;
● IntOperation intOp ;
intOp = x -> x * 2;
Inference by affectation
Type InferenceType Inference
45. public Runnable toDoLater() {
return () -> System.out.println("later");
}
Inference by return type
Type Inference
58. List<Integer> salaries = …
int averageSalaries = ...
for (Integer salary : salaries){
…
}
Legacy
Stream API
Reduce
59. List<Integer> salaries = …
Int averageAge = salaries.streams()
.average();
Functional Style
Stream API
Reduce
60. int sum = shapes.stream()
.filter(s -> s.getColor() == BLUE)
.mapToInt(s -> s.getWeight())
.sum();
Stream API
Pipeline Structure
61. Optional API
Forgetting to check for null references is a
common source of bugs in application code. One
way to eliminate NullPointerExceptions is to
make sure that methods always return a non null
value.
62. Example
User user = userRepository.getUser(“id”);
If (user != null){
user.doSomeThing();
}
Optional API
82. Futher readings
Devoxx
France 2015 : Hadi Hariri (Refactoring to functional)
UK 2014 : Raoul Gabriel Urma && Richard Warburton Pragmatic
Functional Refactoring with Java 8
Books
● Functional programming for Java developers
● Java SE8 for the Really Impatient
● Java 8 in action