SlideShare a Scribd company logo
Simone Bordet
Mario Fusco
OOP and FP
Become a
Better Programmer
Our definition
Of OOP and FP
Simone Bordet
Mario Fusco
Our Definition of OOP
 In this presentation “OOP” will mean:
 Idiomatic Java 7 programming style:
 Use of mutable variables and state
 Use of classes and void methods
 Use of external iteration (for loops)
 Use of threads
Simone Bordet
Mario Fusco
Our definition of FP
 In this presentation “FP” will mean:
 Java 8 programming style, with:
 Immutable variables and state
 Use classes, but avoid void methods
 Internal iteration via Stream
 CompletableFuture, not Thread
Goals
Simone Bordet
Mario Fusco
Goals
 This session is about OOP and FP
 NOT about OOP versus FP
 We want to show that in order to be a better
programmer, you have to know both
 In some cases it's better to apply one paradigm
 In other cases it's better to apply the other
 We will hint at some guideline that helps deciding
Example #1
“accumulator”
Simone Bordet
Mario Fusco
Example #1, v1
public String sum(List<Student> students) {
StringBuilder sb = new StringBuilder();
for (Student s : students)
sb.append(s.getName()).append(“, “);
return sb.toString();
}
 OOP style
 External iteration
 Mutable variables
Simone Bordet
Mario Fusco
Example #1, v2
public String sum(List<Student> students) {
StringBuilder sb = new StringBuilder();
students.stream()
.forEach(s -> sb.append(s.getName()).append(“, “));
return sb.toString();
}
 BAD style
 Use of mutable accumulator
Simone Bordet
Mario Fusco
Example #1, v3
public String sum(List<Student> students) {
String names = students.stream()
.map(s -> s.getName() + “, “)
.reduce(“”, (a, b) -> a + b);
return names;
}
 FP style
 Internal iteration
 Mapping input to output
 No mutable variables
Example #2
“what do you do ?”
Simone Bordet
Mario Fusco
Example #2, v1
 What does this code do ?
List<Student> students = ...;
int min = 0;
for (Student s : students) {
if (s.getGradYear() != 2014)
continue;
int score = s.getGradScore();
if (score > min)
min = score;
}
Simone Bordet
Mario Fusco
Example #2, v2
 Calculates the max, not the min !
 And only for 2014 students !
List<Student> students = ...;
students.stream()
.filter(s -> s.getGradYear() == 2014)
.mapToInt(Student::getScore)
.max();
 Somehow clearer to read
 Less possibility of mistakes
 max() is a method, not a variable name
Simone Bordet
Mario Fusco
Example #2, v3
 But how do you get 2 results iterating once ?
List<Student> students = ...;
int min = Integer.MAX_VALUE, max = 0;
for (Student s : students) {
int score = s.getGradScore();
min = Math.min(min, score);
max = Math.max(max, score);
}
 Easy and readable
Simone Bordet
Mario Fusco
Example #2, v4
 FP version:
 Pair<Integer, Integer> result = students.stream()
.map(s -> new Pair<>(s.getScore(), s.getScore()))
.reduce(new Pair<>(Integer.MAX_VALUE, 0), (acc,elem)-> {
new Pair<>(Math.min(acc._1, elem._1),
Math.max(acc._2, elem._2))
});
 What !?!
Simone Bordet
Mario Fusco
Example #2, v5
 How about parallelizing this ?
Pair<Integer, Integer> result = students.stream().parallel()
.map(s -> new Pair<>(s.getScore(), s.getScore()))
.reduce(new Pair<>(Integer.MAX_VALUE, 0), (acc,elem)-> {
new Pair<>(Math.min(acc._1, elem._1),
Math.max(acc._2, elem._2))
});
 Neat, but .parallel() can only be used under very
strict conditions.
Example #3
“let's group them”
Simone Bordet
Mario Fusco
Example #3, v1
 Group students by their graduation year
Map<Integer, List<Student>> studentByGradYear = new HashMap<>();
for (Student student : students) {
int year = student.getGradYear();
List<Student> list = studentByGradYear.get(year);
if (list == null) {
list = new ArrayList<>();
studentByGradYear.put(year, list);
}
list.add(student);
}
Simone Bordet
Mario Fusco
Example #3, v2
Map<Integer, List<Student>> studentByGradYear =
students.stream()
.collect(groupingBy(student::getGradYear));
Example #4
“separation of concerns”
Simone Bordet
Mario Fusco
Example #4, v1
 Read first 40 error lines from a log file
List<String> errorLines = new ArrayList<>();
int errorCount = 0;
BufferedReader file = new BufferedReader(...);
String line = file.readLine();
while (errorCount < 40 && line != null) {
if (line.startsWith("ERROR")) {
errorLines.add(line);
errorCount++;
}
line = file.readLine();
}
Simone Bordet
Mario Fusco
Example #4, v2
List<String> errors = Files.lines(Paths.get(fileName))
.filter(l -> l.startsWith("ERROR"))
.limit(40)
.collect(toList());
Simone Bordet
Mario Fusco
Example #4
List<String> errorLines = new ArrayList<>();
int errorCount = 0;
BufferedReader file = new BufferedReader(new FileReader(filename));
String line = file.readLine();
while (errorCount < 40 && line != null) {
if (line.startsWith("ERROR")) {
errorLines.add(line);
errorCount++;
}
line = file.readLine();
}
return errorLines;
return Files.lines(Paths.get(fileName))
.filter(l -> l.startsWith("ERROR")
.limit(40)
.collect(toList());
Example #5
“grep -B 1”
Simone Bordet
Mario Fusco
Example #5, v1
 Find lines starting with “ERROR” and previous line
List<String> errorLines = new ArrayList<>();
String previous = null;
String current = reader.readLine();
while (current != null) {
if (current.startsWith("ERROR")) {
if (previous != null)
errorLines.add(previous);
errorLines.add(current);
}
previous = current;
current = reader.readLine();
}
Simone Bordet
Mario Fusco
Example #5, v2
 Not easy – immutability is now an obstacle
 Must read the whole file in memory
 This does not work:
Stream.generate(() -> reader.readLine())
 readLine() throws and can't be used in lambdas
Simone Bordet
Mario Fusco
Example #5, v2
Files.lines(Paths.get(filename))
.reduce(new LinkedList<String[]>(),
(list, line) -> {
if (!list.isEmpty())
list.getLast()[1] = line;
list.offer(new String[]{line, null});
return list;
},
(l1, l2) -> {
l1.getLast()[1] = l2.getFirst()[0];
l1.addAll(l2); return l1;
}).stream()
.filter(ss -> ss[1] != null && ss[1].startsWith("ERROR"))
.collect(Collectors.toList());
Example #6
“callback hell”
Simone Bordet
Mario Fusco
Example #6, v1
 Find a term, in parallel, on many search engines, then execute
an action
final List<SearchEngineResult> result =
new CopyOnWriteArrayList<>();
final AtomicInteger count = new AtomicInteger(engines.size());
for (Engine e : engines) {
http.newRequest(e.url("codemotion")).send(r -> {
String c = r.getResponse().getContentAsString();
result.add(e.parse(c));
boolean finished = count.decrementAndGet() == 0;
if (finished)
lastAction.perform(result);
});
}
Simone Bordet
Mario Fusco
Example #6, v1
 Code smells
 Mutable concurrent accumulators: result and count
 Running the last action within the response callback
 What if http.newRequest() returns a CompletableFuture ?
 Then I would be able to compose those futures !
 Let's try to write it !
Simone Bordet
Mario Fusco
Example #6, v2
CompletableFuture<List<SearchEngineResult>> result =
CompletableFuture.completed(new CopyOnWriteArrayList<>());
for (Engine e : engines) {
CompletableFuture<Response> request =
http.sendRequest(e.url("codemotion"));
result = result.thenCombine(request, (list, response) -> {
String c = response.getContentAsString();
list.add(e.parse(c));
return list;
});
}
result.thenAccept(list -> lastAction.perform(list));
Simone Bordet
Mario Fusco
Example #6, v3
List<CompletableFuture<SearchEngineResult>> results =
engines.stream()
.map(e ->
new Pair<>(e, http.newRequest(e.url("codemotion"))))
.map(p ->
p._2.thenCombine(response ->
p._1.parse(response.getContentAsString())))
.collect(toList());
CompletableFuture.supplyAsync(() -> results.stream()
.map(future -> future.join())
.collect(toList()))
.thenApply(list -> lastAction.perform(list));
Example #7
“statefulness”
Simone Bordet
Mario Fusco
Example #7, v1
class Cat {
private Bird prey;
private boolean full;
void chase(Bird bird) { prey = bird; }
void eat() { prey = null; full = true; }
boolean isFull() { return full; }
}
class Bird {
}
Simone Bordet
Mario Fusco
Example #7, v1
 It is not evident how to use it:
new Cat().eat() ???
 The use case is instead:
Cat useCase(Cat cat, Bird bird) {
cat.chase(bird);
cat.eat();
assert cat.isFull();
return cat;
}
Simone Bordet
Mario Fusco
Example #7, v2
 How about we use types to indicate state ?
class Cat {
CatWithPrey chase(Bird bird) {
return new CatWithPrey(bird);
}
}
class CatWithPrey {
private final Bird prey;
public CatWithPrey(Bird bird) { prey = bird; }
FullCat eat() { return new FullCat(); }
}
class FullCat { }
Simone Bordet
Mario Fusco
Example #7, v2
 Now it is evident how to use it:
FullCat useCase(Cat cat, Bird bird) {
return cat.chase(bird).eat();
}
BiFunction<Cat, Bird, CatWithPrey> chase = Cat::chase;
BiFunction<Cat, Bird, FullCat> useCase =
chase.andThen(CatWithPrey::eat);
 More classes, but clearer semantic
Example #8
“encapsulation”
Simone Bordet
Mario Fusco
Example #8, v1
interface Shape2D {
Shape2D move(int deltax, int deltay)
}
class Circle implements Shape {
private final Point center;
private final int radius;
Circle move(int deltax, int deltay) {
// translate the center
}
}
class Polygon implements Shape {
private final Point[] points;
Polygon move(int deltax, int deltay) {
// Translate each point.
}
}
Simone Bordet
Mario Fusco
Example #8, v1
for (Shape shape : shapes)
shape.move(1, 2);
 How do you do this using an FP language ?
 What is needed is dynamic polymorphism
 Some FP language does not have it
 Other FP languages mix-in OOP features
Simone Bordet
Mario Fusco
Example #8, v2
defn move [shape, deltax, deltay] (
// Must crack open shape, then
// figure out what kind of shape is
// and then translate only the points
)
 OOP used correctly provides encapsulation
 FP must rely on OOP features to provide the same
 Data types are not enough
 Pattern matching is not enough
 Really need dynamic polimorphism
Conclusions
Simone Bordet
Mario Fusco
Conclusions
 If you come from an OOP background
 Study FP
 If you come from an FP background
 Study OOP
 Poly-paradigm programming is more generic,
powerful and effective than polyglot programming.
Simone Bordet
Mario Fusco
Questions
&
Answers

More Related Content

What's hot

Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paper
Deepak Singh
 
C++ L06-Pointers
C++ L06-PointersC++ L06-Pointers
C++ L06-Pointers
Mohammad Shaker
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
Mario Fusco
 
C++ L02-Conversion+enum+Operators
C++ L02-Conversion+enum+OperatorsC++ L02-Conversion+enum+Operators
C++ L02-Conversion+enum+Operators
Mohammad Shaker
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
Zaar Hai
 
C++ L04-Array+String
C++ L04-Array+StringC++ L04-Array+String
C++ L04-Array+String
Mohammad Shaker
 
09. Methods
09. Methods09. Methods
09. Methods
Intro C# Book
 
C++ L09-Classes Part2
C++ L09-Classes Part2C++ L09-Classes Part2
C++ L09-Classes Part2
Mohammad Shaker
 
06.Loops
06.Loops06.Loops
06.Loops
Intro C# Book
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
Intro C# Book
 
Virtual function
Virtual functionVirtual function
Virtual function
harman kaur
 
Lec 42.43 - virtual.functions
Lec 42.43 - virtual.functionsLec 42.43 - virtual.functions
Lec 42.43 - virtual.functions
Princess Sam
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
Intro C# Book
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
rohassanie
 
C++ L08-Classes Part1
C++ L08-Classes Part1C++ L08-Classes Part1
C++ L08-Classes Part1
Mohammad Shaker
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
rohassanie
 
Programs of C++
Programs of C++Programs of C++
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
Olve Maudal
 
OpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpenGurukul : Language : PHP
OpenGurukul : Language : PHP
Open Gurukul
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
rohassanie
 

What's hot (20)

Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paper
 
C++ L06-Pointers
C++ L06-PointersC++ L06-Pointers
C++ L06-Pointers
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
C++ L02-Conversion+enum+Operators
C++ L02-Conversion+enum+OperatorsC++ L02-Conversion+enum+Operators
C++ L02-Conversion+enum+Operators
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
 
C++ L04-Array+String
C++ L04-Array+StringC++ L04-Array+String
C++ L04-Array+String
 
09. Methods
09. Methods09. Methods
09. Methods
 
C++ L09-Classes Part2
C++ L09-Classes Part2C++ L09-Classes Part2
C++ L09-Classes Part2
 
06.Loops
06.Loops06.Loops
06.Loops
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
 
Virtual function
Virtual functionVirtual function
Virtual function
 
Lec 42.43 - virtual.functions
Lec 42.43 - virtual.functionsLec 42.43 - virtual.functions
Lec 42.43 - virtual.functions
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
C++ L08-Classes Part1
C++ L08-Classes Part1C++ L08-Classes Part1
C++ L08-Classes Part1
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
 
Programs of C++
Programs of C++Programs of C++
Programs of C++
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
 
OpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpenGurukul : Language : PHP
OpenGurukul : Language : PHP
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
 

Similar to OOP and FP: become a better programmer - Simone Bordet, Mario Fusco - Codemotion Rome 2015

CSE240 Macros and Preprocessing
CSE240 Macros and PreprocessingCSE240 Macros and Preprocessing
CSE240 Macros and Preprocessing
Garrett Gutierrez
 
DITEC - Programming with Java
DITEC - Programming with JavaDITEC - Programming with Java
DITEC - Programming with Java
Rasan Samarasinghe
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
hwilming
 
Desarrollo para Android con Groovy
Desarrollo para Android con GroovyDesarrollo para Android con Groovy
Desarrollo para Android con Groovy
Software Guru
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptx
AaliyanShaikh
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
ShriKant Vashishtha
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
Srikanth Shreenivas
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in Java
Rasan Samarasinghe
 
[PL] O klasycznej, programistycznej elegancji
[PL] O klasycznej, programistycznej elegancji[PL] O klasycznej, programistycznej elegancji
[PL] O klasycznej, programistycznej elegancji
Jakub Marchwicki
 
Tdd is not about testing
Tdd is not about testingTdd is not about testing
Tdd is not about testing
Gianluca Padovani
 
Spring 2014 CSCI 111 Final exam of 1 61. (2 points) Fl.docx
Spring 2014 CSCI 111 Final exam   of 1 61. (2 points) Fl.docxSpring 2014 CSCI 111 Final exam   of 1 61. (2 points) Fl.docx
Spring 2014 CSCI 111 Final exam of 1 61. (2 points) Fl.docx
rafbolet0
 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
PhanMinhLinhAnxM0190
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
RohitSindhu10
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
AkashdeepBhattacharj1
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
R696
 
Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014
Raimon Ràfols
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?
PVS-Studio
 
Python-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdfPython-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdf
Mohd Aves Malik
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
The Software House
 

Similar to OOP and FP: become a better programmer - Simone Bordet, Mario Fusco - Codemotion Rome 2015 (20)

CSE240 Macros and Preprocessing
CSE240 Macros and PreprocessingCSE240 Macros and Preprocessing
CSE240 Macros and Preprocessing
 
DITEC - Programming with Java
DITEC - Programming with JavaDITEC - Programming with Java
DITEC - Programming with Java
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
 
Desarrollo para Android con Groovy
Desarrollo para Android con GroovyDesarrollo para Android con Groovy
Desarrollo para Android con Groovy
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptx
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in Java
 
[PL] O klasycznej, programistycznej elegancji
[PL] O klasycznej, programistycznej elegancji[PL] O klasycznej, programistycznej elegancji
[PL] O klasycznej, programistycznej elegancji
 
Tdd is not about testing
Tdd is not about testingTdd is not about testing
Tdd is not about testing
 
Spring 2014 CSCI 111 Final exam of 1 61. (2 points) Fl.docx
Spring 2014 CSCI 111 Final exam   of 1 61. (2 points) Fl.docxSpring 2014 CSCI 111 Final exam   of 1 61. (2 points) Fl.docx
Spring 2014 CSCI 111 Final exam of 1 61. (2 points) Fl.docx
 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 
Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?
 
Python-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdfPython-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdf
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 

More from Codemotion

Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Codemotion
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyPompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending story
Codemotion
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaPastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storia
Codemotion
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserPennisi - Essere Richard Altwasser
Pennisi - Essere Richard Altwasser
Codemotion
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Codemotion
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Codemotion
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Codemotion
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 - Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Codemotion
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Codemotion
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Codemotion
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Codemotion
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Codemotion
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Codemotion
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Codemotion
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Codemotion
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
Codemotion
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Codemotion
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Codemotion
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Codemotion
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Codemotion
 

More from Codemotion (20)

Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyPompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending story
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaPastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storia
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserPennisi - Essere Richard Altwasser
Pennisi - Essere Richard Altwasser
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 - Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
 

Recently uploaded

How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
TIPNGVN2
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 

Recently uploaded (20)

How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 

OOP and FP: become a better programmer - Simone Bordet, Mario Fusco - Codemotion Rome 2015

  • 1. Simone Bordet Mario Fusco OOP and FP Become a Better Programmer
  • 3. Simone Bordet Mario Fusco Our Definition of OOP  In this presentation “OOP” will mean:  Idiomatic Java 7 programming style:  Use of mutable variables and state  Use of classes and void methods  Use of external iteration (for loops)  Use of threads
  • 4. Simone Bordet Mario Fusco Our definition of FP  In this presentation “FP” will mean:  Java 8 programming style, with:  Immutable variables and state  Use classes, but avoid void methods  Internal iteration via Stream  CompletableFuture, not Thread
  • 6. Simone Bordet Mario Fusco Goals  This session is about OOP and FP  NOT about OOP versus FP  We want to show that in order to be a better programmer, you have to know both  In some cases it's better to apply one paradigm  In other cases it's better to apply the other  We will hint at some guideline that helps deciding
  • 8. Simone Bordet Mario Fusco Example #1, v1 public String sum(List<Student> students) { StringBuilder sb = new StringBuilder(); for (Student s : students) sb.append(s.getName()).append(“, “); return sb.toString(); }  OOP style  External iteration  Mutable variables
  • 9. Simone Bordet Mario Fusco Example #1, v2 public String sum(List<Student> students) { StringBuilder sb = new StringBuilder(); students.stream() .forEach(s -> sb.append(s.getName()).append(“, “)); return sb.toString(); }  BAD style  Use of mutable accumulator
  • 10. Simone Bordet Mario Fusco Example #1, v3 public String sum(List<Student> students) { String names = students.stream() .map(s -> s.getName() + “, “) .reduce(“”, (a, b) -> a + b); return names; }  FP style  Internal iteration  Mapping input to output  No mutable variables
  • 11. Example #2 “what do you do ?”
  • 12. Simone Bordet Mario Fusco Example #2, v1  What does this code do ? List<Student> students = ...; int min = 0; for (Student s : students) { if (s.getGradYear() != 2014) continue; int score = s.getGradScore(); if (score > min) min = score; }
  • 13. Simone Bordet Mario Fusco Example #2, v2  Calculates the max, not the min !  And only for 2014 students ! List<Student> students = ...; students.stream() .filter(s -> s.getGradYear() == 2014) .mapToInt(Student::getScore) .max();  Somehow clearer to read  Less possibility of mistakes  max() is a method, not a variable name
  • 14. Simone Bordet Mario Fusco Example #2, v3  But how do you get 2 results iterating once ? List<Student> students = ...; int min = Integer.MAX_VALUE, max = 0; for (Student s : students) { int score = s.getGradScore(); min = Math.min(min, score); max = Math.max(max, score); }  Easy and readable
  • 15. Simone Bordet Mario Fusco Example #2, v4  FP version:  Pair<Integer, Integer> result = students.stream() .map(s -> new Pair<>(s.getScore(), s.getScore())) .reduce(new Pair<>(Integer.MAX_VALUE, 0), (acc,elem)-> { new Pair<>(Math.min(acc._1, elem._1), Math.max(acc._2, elem._2)) });  What !?!
  • 16. Simone Bordet Mario Fusco Example #2, v5  How about parallelizing this ? Pair<Integer, Integer> result = students.stream().parallel() .map(s -> new Pair<>(s.getScore(), s.getScore())) .reduce(new Pair<>(Integer.MAX_VALUE, 0), (acc,elem)-> { new Pair<>(Math.min(acc._1, elem._1), Math.max(acc._2, elem._2)) });  Neat, but .parallel() can only be used under very strict conditions.
  • 18. Simone Bordet Mario Fusco Example #3, v1  Group students by their graduation year Map<Integer, List<Student>> studentByGradYear = new HashMap<>(); for (Student student : students) { int year = student.getGradYear(); List<Student> list = studentByGradYear.get(year); if (list == null) { list = new ArrayList<>(); studentByGradYear.put(year, list); } list.add(student); }
  • 19. Simone Bordet Mario Fusco Example #3, v2 Map<Integer, List<Student>> studentByGradYear = students.stream() .collect(groupingBy(student::getGradYear));
  • 21. Simone Bordet Mario Fusco Example #4, v1  Read first 40 error lines from a log file List<String> errorLines = new ArrayList<>(); int errorCount = 0; BufferedReader file = new BufferedReader(...); String line = file.readLine(); while (errorCount < 40 && line != null) { if (line.startsWith("ERROR")) { errorLines.add(line); errorCount++; } line = file.readLine(); }
  • 22. Simone Bordet Mario Fusco Example #4, v2 List<String> errors = Files.lines(Paths.get(fileName)) .filter(l -> l.startsWith("ERROR")) .limit(40) .collect(toList());
  • 23. Simone Bordet Mario Fusco Example #4 List<String> errorLines = new ArrayList<>(); int errorCount = 0; BufferedReader file = new BufferedReader(new FileReader(filename)); String line = file.readLine(); while (errorCount < 40 && line != null) { if (line.startsWith("ERROR")) { errorLines.add(line); errorCount++; } line = file.readLine(); } return errorLines; return Files.lines(Paths.get(fileName)) .filter(l -> l.startsWith("ERROR") .limit(40) .collect(toList());
  • 25. Simone Bordet Mario Fusco Example #5, v1  Find lines starting with “ERROR” and previous line List<String> errorLines = new ArrayList<>(); String previous = null; String current = reader.readLine(); while (current != null) { if (current.startsWith("ERROR")) { if (previous != null) errorLines.add(previous); errorLines.add(current); } previous = current; current = reader.readLine(); }
  • 26. Simone Bordet Mario Fusco Example #5, v2  Not easy – immutability is now an obstacle  Must read the whole file in memory  This does not work: Stream.generate(() -> reader.readLine())  readLine() throws and can't be used in lambdas
  • 27. Simone Bordet Mario Fusco Example #5, v2 Files.lines(Paths.get(filename)) .reduce(new LinkedList<String[]>(), (list, line) -> { if (!list.isEmpty()) list.getLast()[1] = line; list.offer(new String[]{line, null}); return list; }, (l1, l2) -> { l1.getLast()[1] = l2.getFirst()[0]; l1.addAll(l2); return l1; }).stream() .filter(ss -> ss[1] != null && ss[1].startsWith("ERROR")) .collect(Collectors.toList());
  • 29. Simone Bordet Mario Fusco Example #6, v1  Find a term, in parallel, on many search engines, then execute an action final List<SearchEngineResult> result = new CopyOnWriteArrayList<>(); final AtomicInteger count = new AtomicInteger(engines.size()); for (Engine e : engines) { http.newRequest(e.url("codemotion")).send(r -> { String c = r.getResponse().getContentAsString(); result.add(e.parse(c)); boolean finished = count.decrementAndGet() == 0; if (finished) lastAction.perform(result); }); }
  • 30. Simone Bordet Mario Fusco Example #6, v1  Code smells  Mutable concurrent accumulators: result and count  Running the last action within the response callback  What if http.newRequest() returns a CompletableFuture ?  Then I would be able to compose those futures !  Let's try to write it !
  • 31. Simone Bordet Mario Fusco Example #6, v2 CompletableFuture<List<SearchEngineResult>> result = CompletableFuture.completed(new CopyOnWriteArrayList<>()); for (Engine e : engines) { CompletableFuture<Response> request = http.sendRequest(e.url("codemotion")); result = result.thenCombine(request, (list, response) -> { String c = response.getContentAsString(); list.add(e.parse(c)); return list; }); } result.thenAccept(list -> lastAction.perform(list));
  • 32. Simone Bordet Mario Fusco Example #6, v3 List<CompletableFuture<SearchEngineResult>> results = engines.stream() .map(e -> new Pair<>(e, http.newRequest(e.url("codemotion")))) .map(p -> p._2.thenCombine(response -> p._1.parse(response.getContentAsString()))) .collect(toList()); CompletableFuture.supplyAsync(() -> results.stream() .map(future -> future.join()) .collect(toList())) .thenApply(list -> lastAction.perform(list));
  • 34. Simone Bordet Mario Fusco Example #7, v1 class Cat { private Bird prey; private boolean full; void chase(Bird bird) { prey = bird; } void eat() { prey = null; full = true; } boolean isFull() { return full; } } class Bird { }
  • 35. Simone Bordet Mario Fusco Example #7, v1  It is not evident how to use it: new Cat().eat() ???  The use case is instead: Cat useCase(Cat cat, Bird bird) { cat.chase(bird); cat.eat(); assert cat.isFull(); return cat; }
  • 36. Simone Bordet Mario Fusco Example #7, v2  How about we use types to indicate state ? class Cat { CatWithPrey chase(Bird bird) { return new CatWithPrey(bird); } } class CatWithPrey { private final Bird prey; public CatWithPrey(Bird bird) { prey = bird; } FullCat eat() { return new FullCat(); } } class FullCat { }
  • 37. Simone Bordet Mario Fusco Example #7, v2  Now it is evident how to use it: FullCat useCase(Cat cat, Bird bird) { return cat.chase(bird).eat(); } BiFunction<Cat, Bird, CatWithPrey> chase = Cat::chase; BiFunction<Cat, Bird, FullCat> useCase = chase.andThen(CatWithPrey::eat);  More classes, but clearer semantic
  • 39. Simone Bordet Mario Fusco Example #8, v1 interface Shape2D { Shape2D move(int deltax, int deltay) } class Circle implements Shape { private final Point center; private final int radius; Circle move(int deltax, int deltay) { // translate the center } } class Polygon implements Shape { private final Point[] points; Polygon move(int deltax, int deltay) { // Translate each point. } }
  • 40. Simone Bordet Mario Fusco Example #8, v1 for (Shape shape : shapes) shape.move(1, 2);  How do you do this using an FP language ?  What is needed is dynamic polymorphism  Some FP language does not have it  Other FP languages mix-in OOP features
  • 41. Simone Bordet Mario Fusco Example #8, v2 defn move [shape, deltax, deltay] ( // Must crack open shape, then // figure out what kind of shape is // and then translate only the points )  OOP used correctly provides encapsulation  FP must rely on OOP features to provide the same  Data types are not enough  Pattern matching is not enough  Really need dynamic polimorphism
  • 43. Simone Bordet Mario Fusco Conclusions  If you come from an OOP background  Study FP  If you come from an FP background  Study OOP  Poly-paradigm programming is more generic, powerful and effective than polyglot programming.