SlideShare uma empresa Scribd logo
1 de 82
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and Objects
Payel Guria
 

Mais procurados (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
 

Destaque

Testing Javascript - Prasanna K, ThoughtWorks
Testing Javascript - Prasanna K, ThoughtWorksTesting Javascript - Prasanna K, ThoughtWorks
Testing Javascript - Prasanna K, ThoughtWorks
Thoughtworks
 

Destaque (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【 神奇火山大冒險 】
 

Semelhante a 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 beyond
Mario Fusco
 

Semelhante a 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
 

Mais de senejug

Mais 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
 

Último

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Último (20)

5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 

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