Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.
Hjelp, vi skal kode
funksjonelt i Java!
1
JavaZone 2016
Fredrik Vraalsen
fredriv
fredrik.vraalsen@schibsted.com
Kompleksitet
Iboende
Utilsiktet / tilfeldig
4http://i533.photobucket.com/albums/ee339/Sushigirl-94/Funny%20Signs/crazy-sig...
Funksjonell
programmering?© Fredrik Vraalsen 2012
Java 8
Anonyme funksjoner (lambda)
Stream
6
Java 8
Anonyme funksjoner (lambda)
Stream
Optional ?
7
Hva mangler?
Immutability
Value-objekter
Datastrukturer (lister, maps, etc.)
Parallellitet
8
Unngå endring
Verdier kan ikke endres – beregne nye
Dele data fritt
Lettere å resonnere
Ytelsesforbedringer
9
Value-objekter
10https://blog.perbrage.com/2012/04/07/is-it-an-entity-or-a-value-object/
Value-objekter
immutables.io
Lombok
Ren Java
11
immutables.io


public interface Person {

String name();

int age();

}
12
immutables.io
@Value.Immutable

public interface Person {

String name();

int age();

}
13
immutables.io
@Value.Immutable

public interface Person {

String name();

int age();

}
Person person = ImmutablePerson.b...
immutables.io
@Value.Immutable

public interface Person {

String name();

int age();

}
Person person = ...
Person older ...
Lombok


public class Person {

String name;

int age;

}
16
Lombok
@Value

public class Person {

String name;

int age;

}
17
Lombok
@Value

public class Person {

String name;

int age;

}
Person person = new Person("Fredrik", 40);
18
Lombok
@Value

public class Person {

String name;

@Wither int age;

}
Person person = new Person("Fredrik", 40);
Person ...
Utfordringer
Annotation processing
IDE plugins
20
Ren Java
public class Person {

public final String name;

public final int age;



public Person(String name, int age) {
...
Collections
22
© Fredrik Vraalsen 2012
Funksjonelle datastrukturer
Unmodifiable
Immutable
Persistent
23
Immutable
24
123original
Immutable
25
123
123
original
Immutable
26
123
1234new
original
Persistent
27
123original
Persistent
28
123
4new
original
Funksjonelle datastrukturer
pCollections
Javaslang
FunctionalJava
29
pCollections
PStack<String> names = ConsPStack.from(
Arrays.asList("Luke Skywalker”, "Han Solo"));

30
pCollections
PStack<String> names = ConsPStack.from(
Arrays.asList("Luke Skywalker”, "Han Solo”));


PStack<String> moreNa...
pCollections
PStack<String> names = ConsPStack.from(
Arrays.asList("Luke Skywalker”, "Han Solo"));



PStack<String> moreN...
Functional Java
List<String> names = list("Luke Skywalker", "Han Solo");

33
Functional Java
List<String> names = list("Luke Skywalker", "Han Solo");



List<String> moreNames = names.cons("Darth Vad...
Functional Java
List<String> names = list("Luke Skywalker", "Han Solo");



List<String> moreNames = names.cons("Darth Vad...
Javaslang
List<String> names = List.of("Luke Skywalker", "Han Solo");



List<String> moreNames = names.prepend("Darth Vad...
Velge riktig datastruktur
37
Velge riktig datastruktur
38
Velge riktig datastruktur
(Linked)List/Stack vs Vector vs Array
39
Performance
© Fredrik Vraalsen 2012
Streams – performance
List<Article> frontpageArticles =
frontpage.getArticleIds().stream()
.map(id -> fetchArticle(id))
.c...
This one goes to 11!
List<Article> frontpageArticles =
frontpage.getArticleIds().parallelStream()
.map(id -> fetchArticle(...
Starvation
Common F/J thread pool
Workarounds?
Execute within explicit F/J pool
Use CompletableFuture
43
CompletableFuture
Chaining of async futures and actions
Waiting for all or any future(s)
Explicitly complete (like Promise...
To parallelStream or not to …
Batch?
parallelStream FTW!
Interactive? Concurrency?
CompletableFuture FTW!
45
Alternativer
Javaslang Future
FunctionalJava parMap etc.
cyclops-react
Actors
46
For comprehensions
import static javaslang.API.For;
For(

someAsyncTask(),

otherAsyncTask()

)

47
For comprehensions
import static javaslang.API.For;
For(

someAsyncTask(),

otherAsyncTask()

).yield((foo, bar) -> foo + ...
For comprehensions
import static javaslang.API.For;
String result = For(

someAsyncTask(),

otherAsyncTask()

).yield((foo...
Actors
Meldingsbasert
Lokalt = Sekvensiell kø
Flere actors = Parallellitet
50
Actors
Akka
FunctionalJava
51
Andre hjelpemidler
52Enklere Liv / http://painkillerblogg.blogspot.no/2010/10/hjelpemidler.html
Javaslang
Streams = lazy linked lists
Tupler, funksjoner
Option, Either, Future
Feilhåndtering (Try)
Pattern matching
53
Try
Try.of(() -> doSomeWork())
54
Try
Try.of(() -> doSomeWork())
.map(r -> transform(r))
55
Try
Try.of(() -> doSomeWork())
.map(r -> transform(r))
.getOrElse(defaultValue);
56
Try
A result =
Try.of(() -> doSomeWork())
.map(r -> transform(r))
.getOrElse(defaultValue);
57
Either
Kan returnere en av to verdier
Typisk suksess eller feilmelding
58
Either
doComputation() // Either<String, R>
59
Either
doComputation()
.flatMap(r -> toXml(r)) // Either<String, Document>

60
Either
Document result =
doComputation()

.flatMap(r -> toXml(r))

.getOrElseGet(errorMsg -> toErrorXml(errorMsg));

61
jOOλ
Tupler, funksjoner
Seq
62
cyclops-react
Asynkron programmering
Utvidelser av JDK, pCollections, m.m.
Interoperabilitet (AnyM)
63
Functional programming
Enklere kode
Mer robust
Bedre ytelse
Spørsmål?
© Fredrik Vraalsen 2012
fredriv
fredrik.vraalsen@schibsted.com
Hjelp, vi skal kode funksjonelt i Java!
Hjelp, vi skal kode funksjonelt i Java!
Prochain SlideShare
Chargement dans…5
×

Hjelp, vi skal kode funksjonelt i Java!

Java 8 åpnet slusene for funksjonell programmering (FP) i Java, men verktøykassen som følger med JDKen er ganske mangelfull. Man har ingen støtte for immutable objekter og datastrukturer, som er helt essensielt innen FP og hjelper deg å fjerne en rekke typer kodefeil. I tillegg mangler for eksempel mer høynivå mekanismer for parallellisering av oppgaver.

I dette foredraget vil vi gå igjennom et utvalg av tredjepartsbiblioteker som du kan ta i bruk for å bøte på disse problemene og gjøre Java-koden din ennå mer sikker og funksjonell!

  • Identifiez-vous pour voir les commentaires

Hjelp, vi skal kode funksjonelt i Java!

  1. 1. Hjelp, vi skal kode funksjonelt i Java! 1 JavaZone 2016 Fredrik Vraalsen fredriv fredrik.vraalsen@schibsted.com
  2. 2. Kompleksitet Iboende Utilsiktet / tilfeldig 4http://i533.photobucket.com/albums/ee339/Sushigirl-94/Funny%20Signs/crazy-sign-0508141.jpg
  3. 3. Funksjonell programmering?© Fredrik Vraalsen 2012
  4. 4. Java 8 Anonyme funksjoner (lambda) Stream 6
  5. 5. Java 8 Anonyme funksjoner (lambda) Stream Optional ? 7
  6. 6. Hva mangler? Immutability Value-objekter Datastrukturer (lister, maps, etc.) Parallellitet 8
  7. 7. Unngå endring Verdier kan ikke endres – beregne nye Dele data fritt Lettere å resonnere Ytelsesforbedringer 9
  8. 8. Value-objekter 10https://blog.perbrage.com/2012/04/07/is-it-an-entity-or-a-value-object/
  9. 9. Value-objekter immutables.io Lombok Ren Java 11
  10. 10. immutables.io 
 public interface Person {
 String name();
 int age();
 } 12
  11. 11. immutables.io @Value.Immutable
 public interface Person {
 String name();
 int age();
 } 13
  12. 12. immutables.io @Value.Immutable
 public interface Person {
 String name();
 int age();
 } Person person = ImmutablePerson.builder()
 .name("Fredrik")
 .age(40)
 .build(); 14
  13. 13. immutables.io @Value.Immutable
 public interface Person {
 String name();
 int age();
 } Person person = ... Person older = ImmutablePerson.copyOf(person)
 .withAge(41); 15
  14. 14. Lombok 
 public class Person {
 String name;
 int age;
 } 16
  15. 15. Lombok @Value
 public class Person {
 String name;
 int age;
 } 17
  16. 16. Lombok @Value
 public class Person {
 String name;
 int age;
 } Person person = new Person("Fredrik", 40); 18
  17. 17. Lombok @Value
 public class Person {
 String name;
 @Wither int age;
 } Person person = new Person("Fredrik", 40); Person older = person.withAge(41); 19
  18. 18. Utfordringer Annotation processing IDE plugins 20
  19. 19. Ren Java public class Person {
 public final String name;
 public final int age;
 
 public Person(String name, int age) {
 this.name = name;
 this.age = age;
 } // equals, hashCode, withAge, ...
 } 21
  20. 20. Collections 22 © Fredrik Vraalsen 2012
  21. 21. Funksjonelle datastrukturer Unmodifiable Immutable Persistent 23
  22. 22. Immutable 24 123original
  23. 23. Immutable 25 123 123 original
  24. 24. Immutable 26 123 1234new original
  25. 25. Persistent 27 123original
  26. 26. Persistent 28 123 4new original
  27. 27. Funksjonelle datastrukturer pCollections Javaslang FunctionalJava 29
  28. 28. pCollections PStack<String> names = ConsPStack.from( Arrays.asList("Luke Skywalker”, "Han Solo"));
 30
  29. 29. pCollections PStack<String> names = ConsPStack.from( Arrays.asList("Luke Skywalker”, "Han Solo”)); 
 PStack<String> moreNames = names.plus("Darth Vader"); 31
  30. 30. pCollections PStack<String> names = ConsPStack.from( Arrays.asList("Luke Skywalker”, "Han Solo"));
 
 PStack<String> moreNames = names.plus("Darth Vader"); 
 List<String> skywalkers = moreNames .stream()
 .filter(name -> name.contains("Skywalker"))
 .collect(Collectors.toList()); 32
  31. 31. Functional Java List<String> names = list("Luke Skywalker", "Han Solo");
 33
  32. 32. Functional Java List<String> names = list("Luke Skywalker", "Han Solo");
 
 List<String> moreNames = names.cons("Darth Vader");
 34
  33. 33. Functional Java List<String> names = list("Luke Skywalker", "Han Solo");
 
 List<String> moreNames = names.cons("Darth Vader");
 
 List<String> skywalkers = names .filter(name -> name.contains("Skywalker")); 35
  34. 34. Javaslang List<String> names = List.of("Luke Skywalker", "Han Solo");
 
 List<String> moreNames = names.prepend("Darth Vader");
 
 List<String> skywalkers = names .filter(name -> name.contains("Skywalker")); 36
  35. 35. Velge riktig datastruktur 37
  36. 36. Velge riktig datastruktur 38
  37. 37. Velge riktig datastruktur (Linked)List/Stack vs Vector vs Array 39
  38. 38. Performance © Fredrik Vraalsen 2012
  39. 39. Streams – performance List<Article> frontpageArticles = frontpage.getArticleIds().stream() .map(id -> fetchArticle(id)) .collect(toList()); 41
  40. 40. This one goes to 11! List<Article> frontpageArticles = frontpage.getArticleIds().parallelStream() .map(id -> fetchArticle(id)) .collect(toList()); 42
  41. 41. Starvation Common F/J thread pool Workarounds? Execute within explicit F/J pool Use CompletableFuture 43
  42. 42. CompletableFuture Chaining of async futures and actions Waiting for all or any future(s) Explicitly complete (like Promise) Control of executor service 44 http://blog.krecan.net/2014/03/18/how-to-specify-thread-pool-for-java-8-parallel-streams/ http://www.nurkiewicz.com/2013/05/java-8-completablefuture-in-action.html
  43. 43. To parallelStream or not to … Batch? parallelStream FTW! Interactive? Concurrency? CompletableFuture FTW! 45
  44. 44. Alternativer Javaslang Future FunctionalJava parMap etc. cyclops-react Actors 46
  45. 45. For comprehensions import static javaslang.API.For; For(
 someAsyncTask(),
 otherAsyncTask()
 )
 47
  46. 46. For comprehensions import static javaslang.API.For; For(
 someAsyncTask(),
 otherAsyncTask()
 ).yield((foo, bar) -> foo + bar) 48
  47. 47. For comprehensions import static javaslang.API.For; String result = For(
 someAsyncTask(),
 otherAsyncTask()
 ).yield((foo, bar) -> foo + bar).get();
 49
  48. 48. Actors Meldingsbasert Lokalt = Sekvensiell kø Flere actors = Parallellitet 50
  49. 49. Actors Akka FunctionalJava 51
  50. 50. Andre hjelpemidler 52Enklere Liv / http://painkillerblogg.blogspot.no/2010/10/hjelpemidler.html
  51. 51. Javaslang Streams = lazy linked lists Tupler, funksjoner Option, Either, Future Feilhåndtering (Try) Pattern matching 53
  52. 52. Try Try.of(() -> doSomeWork()) 54
  53. 53. Try Try.of(() -> doSomeWork()) .map(r -> transform(r)) 55
  54. 54. Try Try.of(() -> doSomeWork()) .map(r -> transform(r)) .getOrElse(defaultValue); 56
  55. 55. Try A result = Try.of(() -> doSomeWork()) .map(r -> transform(r)) .getOrElse(defaultValue); 57
  56. 56. Either Kan returnere en av to verdier Typisk suksess eller feilmelding 58
  57. 57. Either doComputation() // Either<String, R> 59
  58. 58. Either doComputation() .flatMap(r -> toXml(r)) // Either<String, Document>
 60
  59. 59. Either Document result = doComputation()
 .flatMap(r -> toXml(r))
 .getOrElseGet(errorMsg -> toErrorXml(errorMsg));
 61
  60. 60. jOOλ Tupler, funksjoner Seq 62
  61. 61. cyclops-react Asynkron programmering Utvidelser av JDK, pCollections, m.m. Interoperabilitet (AnyM) 63
  62. 62. Functional programming Enklere kode Mer robust Bedre ytelse
  63. 63. Spørsmål? © Fredrik Vraalsen 2012 fredriv fredrik.vraalsen@schibsted.com

×