SlideShare une entreprise Scribd logo
1  sur  82
Télécharger pour lire hors ligne
Yakhya DABO
Software craftsman && DevOps Engineer
@yakhyadabo
(Birmingham, United Kingdom)
Work & Interests
Continuous Delivery
Work and Interests
Software craftsmanship
Work and Interests
Don't just code Monkey (M. Fowler)
→ Knowledge
→ Responsibility
→ Impact
Work and Interests
Devoxx France
Paris Jug
Socrates Germany
London Software craftsmanship
Communities
Work and Interests
Functional Programming in Java 8
Avoid technical debt
Java 7 is no longer supported
Java 9 coming soon
A programming paradigm that ...
● Treats function as primitive
● Avoids state and mutable data
● Is declarative
Definition of Functional Programming
To be a function
function succ(int y){
return y++;
}
Definition
int x = 1;
function dummy(int y){
x++;
return x+y;
}
Not to be a function
Definition
int x = 1;
function dummy(int y){
x++;
return x+y;
}
Not to be a function
Definition
Functions as First-Class Citizens
- High-Order Functions
- Lambda
- Top-Level Functions
Immutable data
(Hadi Hariri Devoxx France 2015)
Functional Language
Write less and expressive code
Why do we need it ?
The Context
“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
Every 18 months a CPU's transistors will
shrink in size by a factor of two.
Moor Law
The context
- In 2002, limitations in a CPU's circuitry.
- The multi-core processor was born.
Moor Law (New Context)
The context
Lambda project
“Reduce the gap between the serial and parallel
versions of the same computation”
Brian Goetz (Lambda project leader)
The context
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
Output out = input.process(treatment);
Output out = Input.processInParallel(treatment);
Pallelizing with FP
The context
=> Lambda expression
=> Functional Interface
=> Optional API
=> Stream API
….
Java 8 main new features
Lambda expressions
(argument_list) -> function_body
Lambda expression
x -> x + 1 ;
(int x, int y) -> x + y ;
() -> System.out.println("I am a lambda");
Lambda expressions
Lambda expressions
X= (int x) -> x + 1 ;
(int x, int y) -> {
z = x + y ;
z++;
}
Lambda expression
Lambda expressions
Functional Interface
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
int x -> x * 2;
public interface IntOperation {
int operate(int i);
}
Functional Interface
- Function
- Consumer
- Supplier
Functional Interface
Common Functional Interfaces
Functions accept one argument and produce a result.
@FunctionalInterface
Interface Function<T,R>{
R apply(T t);
}
Functional Interface
Function
// String to an integer
Function<String, Integer> stringToInt = x -> Integer.valueOf(x);
int toto = stringToInt(“10”);
Functional Interface
Function
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
Supplier<Person> personSupplier = () -> new Person();
Person persion = personSupplier.get();
Functional Interface
Supplier
Consumers represents operations to be performed on a single
input argument.
@FunctionalInterface
public interface Consumer<T>{
void accept(T t)
}
Functional Interface
Consumer
Consumer<Person> personPrinter =
(p) -> System.out.println("Hello, " + p.firstName);
personPrinter.accept(new Person("Luke", "Skywalker"));
Functional Interface
Consumer
Predicates are boolean-valued functions of one
argument.
@FunctionalInterface
Interface Predicate<T>{
boolean test(T t)
}
Functional Interface
Predicate
Predicate<String> isNotEmpty = s -> s.isEmpty();
Predicate<String> isNotEmpty = isEmpty.negate();
Functional Interface
Predicate
Type Inference
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
Java does have type inferencing when using generics.
public <T> T foo(T t) {
return t;
}
Type Inference
Type Inference
● DoubleOperation doubleOp = x -> x * 2;
● IntOperation intOp = x -> x * 2;
Inference by declaration
Type Inference
● DoubleOperation doubleOp ;
doubleOp = x -> x * 2;
● IntOperation intOp ;
intOp = x -> x * 2;
Inference by affectation
Type InferenceType Inference
public Runnable toDoLater() {
return () -> System.out.println("later");
}
Inference by return type
Type Inference
Object runnable = (Runnable) () ->
{ System.out.println("Hello"); };
Object callable = (Callable) () →
{ System.out.println("Hello"); };
Inference by cast
Type Inference
Stream API
Collections support operations that work on a
single element :
add(), remove() and contains()
Stream API
Streams have bulk operations that access all
elements in a sequence.
forEach(), filter(), map(), and reduce()
Stream API
Three central concepts of functional
programming
Map/Filter/Reduce
Stream API
map(f, [d0, d1, d2...]) -> [f(d0), f(d1), f(d2)...]
Map
Stream API
Legacy
List<String> names = …
List<Person> people = ...
for (Person person : people){
names.add(person.getName());
}
Map
Stream API
List<Person> people = ...
List<String> names = people.streams()
.map(person -> person.getName())
.collect(Collectors.toList());
Functional Style
Map
Stream API
filter(is_even, [1, 2, 7, -4, 3, 12.0001]) -> [2, -4]
Filter
Stream API
List<Person> people = …
List<Person> peopleOver50 = ...
for (Person person : people){
if(person.getAge() >= 50){
peopleOver50.add(person.getName());
}
}
Legacy
Filter
Stream API
List<Person> people = …
List<String> peopleOver50 = people.streams()
.filter(person -> person.getAge()>50)
.collect(Collectors.toList());
Functional Style
Filter
Stream API
reduce(add, [1, 2, 4, 8]) -> 15
Reduce
Stream API
List<Integer> salaries = …
int averageSalaries = ...
for (Integer salary : salaries){
…
}
Legacy
Stream API
Reduce
List<Integer> salaries = …
Int averageAge = salaries.streams()
.average();
Functional Style
Stream API
Reduce
int sum = shapes.stream()
.filter(s -> s.getColor() == BLUE)
.mapToInt(s -> s.getWeight())
.sum();
Stream API
Pipeline Structure
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.
Example
User user = userRepository.getUser(“id”);
If (user != null){
user.doSomeThing();
}
Optional API
With Optional
Optional<User> user = userRepository.getUser(“id”);
If (user.isPresent()){
user.doSomeThing();
}
Optional API
Optional API
Functional style
Optional<User> user = userRepository.getUser(“id”);
user.ifPresent(u - > u.doSomeThing());
Optional API
Functional style
Optional<User> user = userRepository.getUser(“id”);
user.ifPresent(u - > u.doSomeThing());
userRepository.getUser(“id”)
.ifPresent(user - > user.doSomeThing());
Optional<SomeObject> opt = Optional.empty();
Optional<SomeObject> opt = Optional.of(notNull);
Optional<SomeObject> opt = Optional.ofNullable(mayBeNull);
Declaration
Optional API
Common Optional patterns
Optional API
if (x != null && x.contains("ab")) {
print(x);
}
Optional API
If (condition) doSomething
if (x != null && x.contains("ab")) {
print(x);
}
Optional API
If (condition) doSomething
opt
.filter(x -> x.contains("ab"))
.ifPresent(x -> print(x));
Optional API
If (condition) return else return
if (x !=null){
return x.length();
} else {
return -1;
}
Optional API
If (condition) return else return
opt
.map(x -> x.length() )
.orElse(-1);
if (x !=null){
return x.length();
} else {
return -1;
}
if (s != null && !s.isEmpty()){
return s.charAt(0);
else
throw new IllegalArgumentException();
}
Optional API
Throwing Exception
if (s != null && !s.isEmpty()){
return s.charAt(0);
else
throw new IllegalArgumentException();
}
Optional API
Throwing Exception
opt
.filter(s -> ! s.isEmpty()).
.map(s -> s.charAt(0)).
.orElseThrow(IllegalArgumentException::new);
if (x !=null){
print(x.length());
} else {
Print(“-1”);
}
Optional API
If (condition) do else … do
if (x !=null){
print(x.length());
} else {
Print(“-1”);
}
Optional API
If (condition) do else … do
???
Avoid having states
Avoid using for, while
Think twice before using if
Summary
Curryfication, partial functions
Dependency injection
Monad ...
Next step ...
Function<Integer,Function<Integer,Integer>> sum =
x -> y -> x + y;
Function<Integer, Integer> plus10 = sum.apply(10);
Integer res = plus10.apply(5);
… Next step
Curryfication
...
… Next step
Monad
...
… Next step
Dependency injection
...
… Next step
Future of GoF
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

Contenu connexe

Tendances

Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8RichardWarburton
 
More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and ObjectsPayel Guria
 
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions Ganesh Samarthyam
 
Introduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effectsIntroduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effectsJorge Vásquez
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingRasan Samarasinghe
 
Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Vadim Dubs
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testingScott Wlaschin
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in ScalaDamian Jureczko
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScripttmont
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional ProgrammingHugo Firth
 

Tendances (20)

Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
 
Java operators
Java operatorsJava operators
Java operators
 
More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and Objects
 
02basics
02basics02basics
02basics
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
 
Introduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effectsIntroduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effects
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
Java Script Workshop
Java Script WorkshopJava Script Workshop
Java Script Workshop
 
Java generics final
Java generics finalJava generics final
Java generics final
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.
 
Scala functions
Scala functionsScala functions
Scala functions
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testing
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 

En vedette

CLIW 2015-2016 (5/13) Vizualizarea datelor – o privire de ansamblu
CLIW 2015-2016 (5/13) Vizualizarea datelor – o privire de ansambluCLIW 2015-2016 (5/13) Vizualizarea datelor – o privire de ansamblu
CLIW 2015-2016 (5/13) Vizualizarea datelor – o privire de ansambluSabin Buraga
 
Facebook and Myspace App Platforms: A Brief Update
Facebook and Myspace App Platforms: A Brief UpdateFacebook and Myspace App Platforms: A Brief Update
Facebook and Myspace App Platforms: A Brief UpdateO'Reilly Media
 
Inspirational Quotes For The New Year 2016
Inspirational Quotes For The New Year 2016Inspirational Quotes For The New Year 2016
Inspirational Quotes For The New Year 2016Makala D.
 
Testing Javascript - Prasanna K, ThoughtWorks
Testing Javascript - Prasanna K, ThoughtWorksTesting Javascript - Prasanna K, ThoughtWorks
Testing Javascript - Prasanna K, ThoughtWorksThoughtworks
 
Las damas, los niños y el contenido primero - El diseño de experiencia de us...
Las damas, los niños y el contenido primero - El diseño de experiencia  de us...Las damas, los niños y el contenido primero - El diseño de experiencia  de us...
Las damas, los niños y el contenido primero - El diseño de experiencia de us...Emiliano Cosenza
 
人生で大事なことは XP白本と参考文献に教わった
人生で大事なことは XP白本と参考文献に教わった 人生で大事なことは XP白本と参考文献に教わった
人生で大事なことは XP白本と参考文献に教わった Takeshi Kakeda
 
Confianza y Fe - Casa Templaria 04 mayo 2016
Confianza y Fe - Casa Templaria 04  mayo 2016Confianza y Fe - Casa Templaria 04  mayo 2016
Confianza y Fe - Casa Templaria 04 mayo 2016Jardinera Msf
 
広島の楽しい100人 媒体資料
広島の楽しい100人 媒体資料 広島の楽しい100人 媒体資料
広島の楽しい100人 媒体資料 tanoshii100nin
 
[Info2016]01introduction
[Info2016]01introduction[Info2016]01introduction
[Info2016]01introductionJY LEE
 
portfolio
portfolioportfolio
portfolioeextra
 
小V童書系列 08【 神奇火山大冒險 】
小V童書系列 08【 神奇火山大冒險 】小V童書系列 08【 神奇火山大冒險 】
小V童書系列 08【 神奇火山大冒險 】Yu-Ping Su
 

En vedette (18)

Software Audros | Dedicado à Gestão Documental | Apresentação
Software Audros | Dedicado à Gestão Documental | ApresentaçãoSoftware Audros | Dedicado à Gestão Documental | Apresentação
Software Audros | Dedicado à Gestão Documental | Apresentação
 
TDD - Ketan Soni
TDD - Ketan SoniTDD - Ketan Soni
TDD - Ketan Soni
 
GREEN TREE
GREEN TREEGREEN TREE
GREEN TREE
 
CLIW 2015-2016 (5/13) Vizualizarea datelor – o privire de ansamblu
CLIW 2015-2016 (5/13) Vizualizarea datelor – o privire de ansambluCLIW 2015-2016 (5/13) Vizualizarea datelor – o privire de ansamblu
CLIW 2015-2016 (5/13) Vizualizarea datelor – o privire de ansamblu
 
Facebook and Myspace App Platforms: A Brief Update
Facebook and Myspace App Platforms: A Brief UpdateFacebook and Myspace App Platforms: A Brief Update
Facebook and Myspace App Platforms: A Brief Update
 
Inspirational Quotes For The New Year 2016
Inspirational Quotes For The New Year 2016Inspirational Quotes For The New Year 2016
Inspirational Quotes For The New Year 2016
 
Tren Yikama Sistemleri - DBF Otomati̇k Endüstriyel Yikama Sistemleri Tanitimi...
Tren Yikama Sistemleri - DBF Otomati̇k Endüstriyel Yikama Sistemleri Tanitimi...Tren Yikama Sistemleri - DBF Otomati̇k Endüstriyel Yikama Sistemleri Tanitimi...
Tren Yikama Sistemleri - DBF Otomati̇k Endüstriyel Yikama Sistemleri Tanitimi...
 
Testing Javascript - Prasanna K, ThoughtWorks
Testing Javascript - Prasanna K, ThoughtWorksTesting Javascript - Prasanna K, ThoughtWorks
Testing Javascript - Prasanna K, ThoughtWorks
 
O vermelho do amor
O vermelho do amorO vermelho do amor
O vermelho do amor
 
Las damas, los niños y el contenido primero - El diseño de experiencia de us...
Las damas, los niños y el contenido primero - El diseño de experiencia  de us...Las damas, los niños y el contenido primero - El diseño de experiencia  de us...
Las damas, los niños y el contenido primero - El diseño de experiencia de us...
 
Campanha Frotas
Campanha FrotasCampanha Frotas
Campanha Frotas
 
人生で大事なことは XP白本と参考文献に教わった
人生で大事なことは XP白本と参考文献に教わった 人生で大事なことは XP白本と参考文献に教わった
人生で大事なことは XP白本と参考文献に教わった
 
Confianza y Fe - Casa Templaria 04 mayo 2016
Confianza y Fe - Casa Templaria 04  mayo 2016Confianza y Fe - Casa Templaria 04  mayo 2016
Confianza y Fe - Casa Templaria 04 mayo 2016
 
Ama la vida
Ama la vidaAma la vida
Ama la vida
 
広島の楽しい100人 媒体資料
広島の楽しい100人 媒体資料 広島の楽しい100人 媒体資料
広島の楽しい100人 媒体資料
 
[Info2016]01introduction
[Info2016]01introduction[Info2016]01introduction
[Info2016]01introduction
 
portfolio
portfolioportfolio
portfolio
 
小V童書系列 08【 神奇火山大冒險 】
小V童書系列 08【 神奇火山大冒險 】小V童書系列 08【 神奇火山大冒險 】
小V童書系列 08【 神奇火山大冒險 】
 

Similaire à SeneJug java_8_prez_122015

FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonCodemotion
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8franciscoortin
 
Dev Concepts: Functional Programming
Dev Concepts: Functional ProgrammingDev Concepts: Functional Programming
Dev Concepts: Functional ProgrammingSvetlin Nakov
 
Function in c program
Function in c programFunction in c program
Function in c programumesh patil
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Sheik Uduman Ali
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 
NLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaNLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaMartijn Blankestijn
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...Akaks
 
Computer-programming-User-defined-function-1.pptx
Computer-programming-User-defined-function-1.pptxComputer-programming-User-defined-function-1.pptx
Computer-programming-User-defined-function-1.pptxJohnRehldeGracia
 

Similaire à SeneJug java_8_prez_122015 (20)

FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Unit 4 (1)
Unit 4 (1)Unit 4 (1)
Unit 4 (1)
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 
Dev Concepts: Functional Programming
Dev Concepts: Functional ProgrammingDev Concepts: Functional Programming
Dev Concepts: Functional Programming
 
Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
C# programming
C# programming C# programming
C# programming
 
NLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaNLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by Ordina
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
 
Computer-programming-User-defined-function-1.pptx
Computer-programming-User-defined-function-1.pptxComputer-programming-User-defined-function-1.pptx
Computer-programming-User-defined-function-1.pptx
 
Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
 

Plus de senejug

BIG DATA - Cloud Computing
BIG DATA - Cloud ComputingBIG DATA - Cloud Computing
BIG DATA - Cloud Computingsenejug
 
Demonstration of @mail@
Demonstration of @mail@Demonstration of @mail@
Demonstration of @mail@senejug
 
L'approche par regles metier
L'approche par regles metierL'approche par regles metier
L'approche par regles metiersenejug
 
Archivage Electronique: Comment Ca Marche?
Archivage Electronique: Comment Ca Marche?Archivage Electronique: Comment Ca Marche?
Archivage Electronique: Comment Ca Marche?senejug
 
Développement agile de logiciel avec la méthode SCRUM
Développement agile de logiciel avec la méthode SCRUMDéveloppement agile de logiciel avec la méthode SCRUM
Développement agile de logiciel avec la méthode SCRUMsenejug
 
West Africa Apple Development
West Africa Apple DevelopmentWest Africa Apple Development
West Africa Apple Developmentsenejug
 
Biometrics
BiometricsBiometrics
Biometricssenejug
 
Solution de gestion de paie : PAYOHR
Solution de gestion de paie : PAYOHRSolution de gestion de paie : PAYOHR
Solution de gestion de paie : PAYOHRsenejug
 
Business Intelligence
Business IntelligenceBusiness Intelligence
Business Intelligencesenejug
 
Intégration d\'applications pour call centers
Intégration d\'applications pour call centersIntégration d\'applications pour call centers
Intégration d\'applications pour call centerssenejug
 
Capital Risk & IT, The Perfect Connection?
Capital Risk & IT, The Perfect Connection?Capital Risk & IT, The Perfect Connection?
Capital Risk & IT, The Perfect Connection?senejug
 
Telecom in West Africa: Trends and Challenges
Telecom in West Africa: Trends and ChallengesTelecom in West Africa: Trends and Challenges
Telecom in West Africa: Trends and Challengessenejug
 
What is Ajax
What is AjaxWhat is Ajax
What is Ajaxsenejug
 
Tips on Creating Web Content
Tips on Creating Web ContentTips on Creating Web Content
Tips on Creating Web Contentsenejug
 
Using CMS Tool Drupal
Using CMS Tool DrupalUsing CMS Tool Drupal
Using CMS Tool Drupalsenejug
 
Web2 And Java
Web2 And JavaWeb2 And Java
Web2 And Javasenejug
 

Plus de senejug (17)

BIG DATA - Cloud Computing
BIG DATA - Cloud ComputingBIG DATA - Cloud Computing
BIG DATA - Cloud Computing
 
Demonstration of @mail@
Demonstration of @mail@Demonstration of @mail@
Demonstration of @mail@
 
L'approche par regles metier
L'approche par regles metierL'approche par regles metier
L'approche par regles metier
 
Archivage Electronique: Comment Ca Marche?
Archivage Electronique: Comment Ca Marche?Archivage Electronique: Comment Ca Marche?
Archivage Electronique: Comment Ca Marche?
 
Développement agile de logiciel avec la méthode SCRUM
Développement agile de logiciel avec la méthode SCRUMDéveloppement agile de logiciel avec la méthode SCRUM
Développement agile de logiciel avec la méthode SCRUM
 
West Africa Apple Development
West Africa Apple DevelopmentWest Africa Apple Development
West Africa Apple Development
 
Biometrics
BiometricsBiometrics
Biometrics
 
Solution de gestion de paie : PAYOHR
Solution de gestion de paie : PAYOHRSolution de gestion de paie : PAYOHR
Solution de gestion de paie : PAYOHR
 
GMAO
GMAOGMAO
GMAO
 
Business Intelligence
Business IntelligenceBusiness Intelligence
Business Intelligence
 
Intégration d\'applications pour call centers
Intégration d\'applications pour call centersIntégration d\'applications pour call centers
Intégration d\'applications pour call centers
 
Capital Risk & IT, The Perfect Connection?
Capital Risk & IT, The Perfect Connection?Capital Risk & IT, The Perfect Connection?
Capital Risk & IT, The Perfect Connection?
 
Telecom in West Africa: Trends and Challenges
Telecom in West Africa: Trends and ChallengesTelecom in West Africa: Trends and Challenges
Telecom in West Africa: Trends and Challenges
 
What is Ajax
What is AjaxWhat is Ajax
What is Ajax
 
Tips on Creating Web Content
Tips on Creating Web ContentTips on Creating Web Content
Tips on Creating Web Content
 
Using CMS Tool Drupal
Using CMS Tool DrupalUsing CMS Tool Drupal
Using CMS Tool Drupal
 
Web2 And Java
Web2 And JavaWeb2 And Java
Web2 And Java
 

Dernier

SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
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
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
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
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
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
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
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
 
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
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 

Dernier (20)

SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
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...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
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
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
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...
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
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...
 
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)
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
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
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 

SeneJug java_8_prez_122015

  • 1. Yakhya DABO Software craftsman && DevOps Engineer @yakhyadabo (Birmingham, United Kingdom)
  • 5. Don't just code Monkey (M. Fowler) → Knowledge → Responsibility → Impact Work and Interests
  • 6. Devoxx France Paris Jug Socrates Germany London Software craftsmanship Communities Work and Interests
  • 8. Avoid technical debt Java 7 is no longer supported Java 9 coming soon
  • 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
  • 14. Write less and expressive code Why do we need it ?
  • 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
  • 26. x -> x + 1 ; (int x, int y) -> x + y ; () -> System.out.println("I am a lambda"); Lambda expressions Lambda expressions
  • 27. X= (int x) -> x + 1 ; (int x, int y) -> { z = x + y ; z++; } Lambda expression Lambda expressions
  • 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
  • 31. - Function - Consumer - Supplier Functional Interface Common Functional Interfaces
  • 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
  • 35. Supplier<Person> personSupplier = () -> new Person(); Person persion = personSupplier.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
  • 37. Consumer<Person> personPrinter = (p) -> System.out.println("Hello, " + p.firstName); personPrinter.accept(new Person("Luke", "Skywalker")); Functional Interface Consumer
  • 38. Predicates are boolean-valued functions of one argument. @FunctionalInterface Interface Predicate<T>{ boolean test(T t) } Functional Interface Predicate
  • 39. Predicate<String> isNotEmpty = s -> s.isEmpty(); Predicate<String> isNotEmpty = isEmpty.negate(); Functional Interface Predicate
  • 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
  • 46. Object runnable = (Runnable) () -> { System.out.println("Hello"); }; Object callable = (Callable) () → { System.out.println("Hello"); }; Inference by cast Type Inference
  • 48. Collections support operations that work on a single element : add(), remove() and contains() Stream API
  • 49. Streams have bulk operations that access all elements in a sequence. forEach(), filter(), map(), and reduce() Stream API
  • 50. Three central concepts of functional programming Map/Filter/Reduce Stream API
  • 51. map(f, [d0, d1, d2...]) -> [f(d0), f(d1), f(d2)...] Map Stream API
  • 52. Legacy List<String> names = … List<Person> people = ... for (Person person : people){ names.add(person.getName()); } Map Stream API
  • 53. List<Person> people = ... List<String> names = people.streams() .map(person -> person.getName()) .collect(Collectors.toList()); Functional Style Map Stream API
  • 54. filter(is_even, [1, 2, 7, -4, 3, 12.0001]) -> [2, -4] Filter Stream API
  • 55. List<Person> people = … List<Person> peopleOver50 = ... for (Person person : people){ if(person.getAge() >= 50){ peopleOver50.add(person.getName()); } } Legacy Filter Stream API
  • 56. List<Person> people = … List<String> peopleOver50 = people.streams() .filter(person -> person.getAge()>50) .collect(Collectors.toList()); Functional Style Filter Stream API
  • 57. reduce(add, [1, 2, 4, 8]) -> 15 Reduce Stream API
  • 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
  • 63. With Optional Optional<User> user = userRepository.getUser(“id”); If (user.isPresent()){ user.doSomeThing(); } Optional API
  • 64. Optional API Functional style Optional<User> user = userRepository.getUser(“id”); user.ifPresent(u - > u.doSomeThing());
  • 65. Optional API Functional style Optional<User> user = userRepository.getUser(“id”); user.ifPresent(u - > u.doSomeThing()); userRepository.getUser(“id”) .ifPresent(user - > user.doSomeThing());
  • 66. Optional<SomeObject> opt = Optional.empty(); Optional<SomeObject> opt = Optional.of(notNull); Optional<SomeObject> opt = Optional.ofNullable(mayBeNull); Declaration Optional API
  • 68. if (x != null && x.contains("ab")) { print(x); } Optional API If (condition) doSomething
  • 69. if (x != null && x.contains("ab")) { print(x); } Optional API If (condition) doSomething opt .filter(x -> x.contains("ab")) .ifPresent(x -> print(x));
  • 70. Optional API If (condition) return else return if (x !=null){ return x.length(); } else { return -1; }
  • 71. Optional API If (condition) return else return opt .map(x -> x.length() ) .orElse(-1); if (x !=null){ return x.length(); } else { return -1; }
  • 72. if (s != null && !s.isEmpty()){ return s.charAt(0); else throw new IllegalArgumentException(); } Optional API Throwing Exception
  • 73. if (s != null && !s.isEmpty()){ return s.charAt(0); else throw new IllegalArgumentException(); } Optional API Throwing Exception opt .filter(s -> ! s.isEmpty()). .map(s -> s.charAt(0)). .orElseThrow(IllegalArgumentException::new);
  • 74. if (x !=null){ print(x.length()); } else { Print(“-1”); } Optional API If (condition) do else … do
  • 75. if (x !=null){ print(x.length()); } else { Print(“-1”); } Optional API If (condition) do else … do ???
  • 76. Avoid having states Avoid using for, while Think twice before using if Summary
  • 77. Curryfication, partial functions Dependency injection Monad ... Next step ...
  • 78. Function<Integer,Function<Integer,Integer>> sum = x -> y -> x + y; Function<Integer, Integer> plus10 = sum.apply(10); Integer res = plus10.apply(5); … Next step Curryfication
  • 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