Movatterモバイル変換


[0]ホーム

URL:


SlideShare a Scribd company logo

Java SE 8 best practices

328 likes100,968 views
Stephen Colebourne
Stephen Colebourne

Lambdas and streams are key new features in Java 8. Lambdas allow blocks of code to be passed around as if they were objects. Streams provide an abstraction for processing collections of objects in a declarative way using lambdas. Optional is a new class that represents null-safe references and helps avoid null pointer exceptions. Checked exceptions can cause issues with lambdas, so helper methods are recommended to convert checked exceptions to unchecked exceptions.

1 of 88
Downloaded 2,173 times
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
Java SE 8 Best PracticesA personal viewpointStephen Colebourne, October 2015
Agenda● ⇒ Introduction● λ Lambdas● f⒳ Functional interfaces● ! Exceptions● ? Optional● ♒ Streams● I Interfaces● Date and Time● Extras
Introduction⇒
Introduction● What is a Best Practice?
Introduction● What is a Best Practice?"commercial or professional proceduresthat are accepted or prescribed as beingcorrect or most effective"
Introduction● What is the Best Practice for Java SE 8?
Introduction● What is the Best Practice for Java SE 8?"whatever I say in the next 50 minutes"
Introduction● Software Best Practice is mostly opinion● Different conclusions perfectly possible● My opinions are based on over a year using Java SE 8
Introduction● Software Best Practice is mostly opinion● Different conclusions perfectly possible● My opinions are based on over a year using Java SE 8But you must exercise your own judgement!
Java SE 8 version● Use Java SE 8 update 40 or later○ preferably use the latest available● Earlier versions have annoying lambda/javac issuesBestPractice
Lambdasλ
Lambdas● Block of code○ like an anonymous inner class● Always assigned to a Functional Interface○ an interface with one abstract method● Uses target typing○ context determines type of the lambda
Lambdas - Example// Java 7List<Person> people = loadPeople();Collections.sort(people, new Comparator<Person>() {@Overridepublic int compare(Person p1, Person p2) {return p1.name.compareTo(p2.name);}});
Lambdas - Example// Java 7List<Person> people = loadPeople();Collections.sort(people, new Comparator<Person>() {@Overridepublic int compare(Person p1, Person p2) {return p1.name.compareTo(p2.name);}});
Lambdas - Example// Java 8List<Person> people = loadPeople();Collections.sort(people,(Person p1, Person p2)p1.name.compareTo(p2.name));
Lambdas - Example// Java 8List<Person> people = loadPeople();Collections.sort(people,(Person p1, Person p2) -> p1.name.compareTo(p2.name));
Lambdas - Example// Java 8List<Person> people = loadPeople();Collections.sort(people,(Person p1, Person p2) -> p1.name.compareTo(p2.name));
Lambdas - Example// Java 8List<Person> people = loadPeople();Collections.sort(people,(p1, p2) -> p1.name.compareTo(p2.name));
Lambdas - Example// Java 8List<Person> people = loadPeople();people.sort((p1, p2) -> p1.name.compareTo(p2.name));
Lambdas● Make use of parameter type inference● Only specify the types when compiler needs it// prefer(p1, p2) -> p1.name.compareTo(p2.name);// avoid(Person p1, Person p2) -> p1.name.compareTo(p2.name);BestPractice
Lambdas● Do not use parameter brackets when optional// preferstr -> str.toUpperCase(Locale.US);// avoid(str) -> str.toUpperCase(Locale.US);BestPractice
Lambdas● Do not declare local variables as 'final'● Use new "effectively final" conceptpublic UnaryOperator<String> upperCaser(Locale locale) {return str -> str.toUpperCase(locale);}BestPracticeDo not declare as 'final'
Lambdas● Prefer expression lambdas over block lambdas● Use a separate method if necessary// preferstr -> str.toUpperCase(Locale.US);// use with carestr -> {return str.toUpperCase(Locale.US);}BestPractice
Lambas for Abstraction● Two large methods contain same code● Except for one bit in the middle● Can use a lambda to express the difference
Lambas for Abstractionprivate int doFoo() {// lots of code// logic specific to method1// lots of code}private int doBar() {// lots of code// logic specific to method2// lots of code}
Lambas for Abstractionprivate int doFoo() {return doFooBar( lambdaOfFooSpecificLogic );}private int doFooBar(Function<A, B> fn) {// lots of coderesult = fn.apply(arg)// lots of code}BestPractice
Example Abstractiondouble[][] res = new double[rowCount][colCount];for (int i = 0; i < rowCount; ++i) {for (int j = 0; j < colCount; ++j) {res[i][j] = pp.getCoefMatrix().get(i, j) * (nCoefs - j - 1);}}DoubleMatrix2D coef = new DoubleMatrix2D(res);
Example AbstractionDoubleMatrix2D coef = DoubleMatrix2D.of(rowCount,colCount,(i, j) -> pp.getCoefMatrix().get(i, j) * (nCoefs - j - 1));// new methodpublic static DoubleMatrix2D of(int rows, int columns, IntIntToDoubleFunction valueFunction)
Functional interfacesf⒳
Functional interfaces● An interface with a single abstract method○ Runnable○ Comparable○ Callable● Java SE 8 adds many new functional interfaces○ Function<T, R>○ Predicate<T>○ Supplier<T>○ Consumer<T>○ see java.util.function package
Functional interfaces● Learn java.util.function package interface● Only write your own if extra semantics are valuable● If writing one, use @FunctionalInterface@FunctionalInterfacepublic interface FooBarQuery {public abstract Foo findAllFoos(Bar bar);}BestPractice
Higher order methods● Methods accepting lambdas are nothing special○ declared type is just a normal interface● However there are some subtletiesprivate String nameGreet(Supplier<String> nameSupplier) {return "Hello " + nameSupplier.get();}// caller can use a lambdaString greeting = nameGreet(() -> "Bob");
Avoid method overloads● Lambdas use target typing● Clashes with method overloading// avoidpublic class Foo<T> {public Foo<R> apply(Function<T, R> fn);public Foo<T> apply(UnaryOperator<T> fn);}
Avoid method overloads● Lambdas use target typing● Clashes with method overloading● Use different method names to avoid clashesBestPractice// preferpublic class Foo<T> {public Foo<R> applyFunction(Function<T, R> fn);public Foo<T> applyOperator(UnaryOperator<T> fn);}
Functional interface last● Prefer to have functional interface last○ when method takes mixture of FI and non-FI● Mostly stylistic○ slightly better IDE error recoveryBestPractice// preferpublic Foo parse(Locale locale, Function<Locale,Foo> fn);// avoidpublic Foo parse(Function<Locale,Foo> fn, Locale locale);
Exceptions!
Checked exceptions● Most functional interfaces do not declare exceptions● No simple way to put checked exceptions in lambdas// does not compile!public Function<String, Class> loader() {return className -> Class.forName(className);}Throws a checked exception
Checked exceptions● Write or find a helper method● Converts checked exception to uncheckedpublic Function<String, Class> loader() {return Unchecked.function(className -> Class.forName(className));}BestPractice
Checked exceptions● Helper methods can deal with any block of code○ convert to runtime exceptions● May be a good case for a block lambdaUnchecked.wrap(() -> {// any code that might throw a checked exception});
Testing for exceptions● Complete unit tests often need to test for exceptionspublic void testConstructorRejectsEmptyString() {try {new FooBar("");fail();} catch (IllegalArgumentException ex) {// expected}}
Testing for exceptions● Use a helper method● Lots of variations on this theme are possiblepublic void testConstructorRejectsEmptyString() {TestHelper.assertThrows(IllegalArgumentException.class, () -> new FooBar(""));}BestPractice
Optional and null?
https://www.flickr.com/photos/bigmacsc99/4003751542/Boom!
Optional and null● New class 'Optional' added to Java 8● Polarizes opinions○ functional programming dudes think it is the saviour of the universe● Simple concept - two states○ present, with a value - Optional.of(foo)○ empty - Optional.empty()
Optional and null● Standard code using null// library, returns null if not foundpublic Foo findFoo(String key) { … }// application codeFoo foo = findFoo(key);if (foo == null) {foo = Foo.DEFAULT; // or throw an exception}
Optional and null● Standard code using Optional// library, returns null if not foundpublic Optional<Foo> findFoo(String key) { … }// application codeFoo foo = findFoo(key).orElse(Foo.DEFAULT);// orFoo foo = findFoo(key).orElseThrow(RuntimeException::new);
Optional and null● Variable of type Optional must never be null● Never ever● Never, never, never, never!BestPractice
Optional● Prefer "functional" methods like 'orElse()'● using 'isPresent()' a lot is misusing the featureBestPractice// preferFoo foo = findFoo(key).orElse(Foo.DEFAULT);// avoidOptional<Foo> optFoo = findFoo(key);if (optFoo.isPresent()) { … }
Optional● Have a discussion and choose an approachA. Use everywhereB. Use instead of null on public APIs, input and outputC. Use instead of null on public return typesD. Use in a few selected placesE. Do not useBestPractice
Optional● Have a discussion and choose an approachA. Use everywhereB. Use instead of null on public APIs, input and outputC. Use instead of null on public return types↖ my preferred choice ↗D. Use in a few selected placesE. Do not useBestPractice
Optional● Optional is a class● Some memory/performance cost to using it● Not serializable● Not ideal to be an instance variable● JDK authors added it for return types● Use in parameters often annoying for callers● Use as return type gets best value from concepthttp://blog.joda.org/2015/08/java-se-8-optional-pragmatic-approach.html
Streams♒
Streams● Most loops are the same● Repetitive design patterns● Stream library provides an abstraction● Lambdas used to pass the interesting bits
StreamsList<Trade> trades = loadTrades();List<Money> valued = new ArrayList<Money>();for (Trade t : trades) {if (t.isActive()) {Money pv = presentValue(t);valued.add(pv);}}Loop to build outputlist from inputOnly interested insome tradesConverts each tradeto the money value
StreamsList<Trade> trades = loadTrades();List<Money> valued = new ArrayList<Money>();for (Trade t : trades) {if (t.isActive()) {Money pv = presentValue(t);valued.add(pv);}}
StreamsList<Trade> trades = loadTrades();List<Money> valued = new ArrayList<Money>();for (Trade t : trades) {if (t.isActive()) {Money pv = presentValue(t);valued.add(pv);}}
StreamsList<Trade> trades = loadTrades();List<Money> valued = Listtradest.isActive()presentValue(t)
StreamsList<Trade> trades = loadTrades();List<Money> valued = // List// trades// t.isActive()// presentValue(t)
StreamsList<Trade> trades = loadTrades();List<Money> valued = // Listtrades.stream() // trades// t.isActive()// presentValue(t)
StreamsList<Trade> trades = loadTrades();List<Money> valued = // Listtrades.stream() // trades.filter(t -> t.isActive()) // t.isActive()// presentValue(t)
StreamsList<Trade> trades = loadTrades();List<Money> valued = // Listtrades.stream() // trades.filter(t -> t.isActive()) // t.isActive().map(t -> presentValue(t)) // presentValue(t)
StreamsList<Trade> trades = loadTrades();List<Money> valued = // Listtrades.stream() // trades.filter(t -> t.isActive()) // t.isActive().map(t -> presentValue(t)) // presentValue(t).collect(Collectors.toList());
StreamsList<Trade> trades = loadTrades();List<Money> valued =trades.stream().filter(t -> t.isActive()).map(t -> presentValue(t)).collect(Collectors.toList());
Streams● Streams are great, sometimes● Important not to get carried away● Design focus was on Collections, not Maps● Key goal was simple parallelism
StreamsList<Trade> trades = loadTrades();List<Money> valued =trades.stream().filter(t -> t.isActive()).map(t -> presentValue(t)).collect(Collectors.toList());
StreamsList<Trade> trades = loadTrades();List<Money> valued =trades.parallelStream().filter(t -> t.isActive()).map(t -> presentValue(t)).collect(Collectors.toList());
Streams● Do not overdo it● Stream not always more readable than loop● Good for Collections, less so for Maps● Don't obsess about method references○ IntelliJ hint may not be the best ideaBestPractice
Streams● Benchmark use in performance critical sections● Parallel streams must be used with great care● Shared execution pool can be deceivingBestPractice
StreamsList<Trade> trades = loadTrades();Predicate<Trade> activePredicate = t -> t.isActive();Function<Trade, Money> valueFn = t -> presentValue(t);List<Money> valued =trades.stream().filter(activePredicate).map(valueFn).collect(Collectors.toList());TopTip● Extract lines if struggling to get to compile
StreamsList<Trade> trades = loadTrades();List<Money> valued =trades.stream().filter(t.isActive()).map((Trade t) -> presentValue(t)).collect(Collectors.toList());● Sometimes compiler needs a type hintTopTip
Streams● Learn to love 'Collector' interface● Complex, but useful● Sometime necessary to write them● Need collectors for Guava 'ImmutableList' and friends○ see 'Guavate' class in OpenGamma Strata
InterfacesI
Interfaces● Now have super-powers● Default methods○ normal method, but on an interface● Static methods○ normal static method, but on an interface● Extend interfaces without breaking compatibility● Cannot default equals/hashCode/toString
Interfaces● New macro-design options● Instead of factory class, use static method on interface● Instead of abstract class, use interface with defaults● Result tends to be fewer classes and better APITopTip
Interfaces● If factory method is static on interface● And all API methods are on interface● Can implementation class be package scoped?BestPractice
Coding Style● Use modifiers in interfaces● Much clearer now there are different types of method● Prepares for possible future with non-public methodsBestPracticepublic interface Foo {public static of(String key) { … }public abstract getKey();public default isActive() { … }}
Date and Time
Date and Time● New Date and Time API - JSR 310● Covers dates, times, instants, periods, durations● Brings 80%+ of Joda-Time to the JDK● Fixes the mistakes in Joda-Time
Date and TimeClass Date Time ZoneOffset ZoneId ExampleLocalDate ✔ ❌ ❌ ❌ 2015-12-03LocalTime ❌ ✔ ❌ ❌ 11:30LocalDateTime ✔ ✔ ❌ ❌ 2015-12-03T11:30OffsetDateTime ✔ ✔ ✔ ❌ 2015-12-03T11:30+01:00ZonedDateTime ✔ ✔ ✔ ✔ 2015-12-03T11:30+01:00[Europe/London]Instant ❌ ❌ ❌ ❌ 123456789 nanos from1970-01-01T00:00Z
Date and Time● Move away from Joda-Time● Avoid java.util.Date and java.util.Calendar● Use ThreeTen-Extra project if necessary○ http://www.threeten.org/threeten-extra/● Focus on four most useful types○ LocalDate, LocalTime, ZonedDateTime, Instant● Network formats like XML/JSON use offset types○ OffsetTime, OffsetDateTimeBestPractice
Date and Time● Temporal interfaces are low-level● Use concrete typesBestPractice// preferLocalDate date = LocalDate.of(2015, 10, 15);// avoidTemporal date = LocalDate.of(2015, 10, 15);
Rocket powered
Other features● Base64● Arithmetic without numeric overflow● Unsigned arithmetic● StampedLock● CompletableFuture● LongAdder/LongAccumulator● Enhanced control of OS processes
Other Features● Enhanced annotations● Reflection on method parameters● No PermGen in Hotspot JVM● Nashorn JavaScript● JavaFX is finally ready to replace Swing
Try a Java 8 open source library● JOOL○ https://github.com/jOOQ/jOOL● ThrowingLambdas○ https://github.com/fge/throwing-lambdas● Parts of OpenGamma Strata (strata-collect - Guavate)○ https://github.com/OpenGamma/Strata● But beware excessively functional ones○ most push ideas that don't really work well in Java
Immutability● Favour immutable classes● Lambdas and streams prefer this● Preparation for value types (Java 10?)● Use Joda-Beans to generate immutable "beans"○ http://www.joda.org/joda-beans/
SummaryJ8
Summary● Java 8 is great● Can be quite different to Java 7 and earlier● Vital to rethink coding style and standards○ methods on interfaces make a big difference● Beware the functional programming/Scala dudes○ a lot of their advice is simply not appropriate for Java
Ad

Recommended

PDF
[OKKYCON] 정진욱 - 테스트하기 쉬운 코드로 개발하기
OKKY
 
PPT
Iterator Design Pattern
Varun Arora
 
PPTX
Kotlin
YeldosTanikin
 
PPSX
Strings in Java
Hitesh-Java
 
PPTX
Writing and using Hamcrest Matchers
Shai Yallin
 
PPT
Core java concepts
Ram132
 
PPTX
Introduction to Koltin for Android Part I
Atif AbbAsi
 
PPTX
Functional programming with Java 8
LivePerson
 
PPTX
Clean code slide
Anh Huan Miu
 
PPTX
Dynamically Generate a CRUD Admin Panel with Java Annotations
Broadleaf Commerce
 
PPT
Oop java
Minal Maniar
 
PPTX
This keyword in java
Hitesh Kumar
 
PDF
#"button" data-testid="button" aria-checked="false" aria-label="Save #" role="switch" aria-haspopup="dialog" aria-controls=":Rfbdc9r6:" popovertarget=":Rfbdc9r6:">
Gustavo Zimmermann
 
PPTX
Clean code
Mahmoud Zizo
 
PPSX
Kotlin Language powerpoint show file
Saurabh Tripathi
 
PDF
Coding with golang
HannahMoss14
 
PDF
Programação Orientada a Objetos (POO) com PHP - Parte 1
Israel Messias
 
PPT
Abstract class in java
Lovely Professional University
 
PPTX
[OKKY 세미나] 정진욱 - 테스트하기 쉬운 코드로 개발하기
OKKY
 
PPSX
Elements of Java Language
Hitesh-Java
 
PDF
C# で Single Page Web アプリが開発できるフレームワーク&開発環境 「Blazor」 ― その概要と Web アプリ開発者にもたらす利点
Jun-ichi Sakamoto
 
PDF
Java modules
Rory Preddy
 
PPSX
Arrays in Java
Hitesh-Java
 
PPTX
JRE , JDK and platform independent nature of JAVA
Mehak Tawakley
 
PDF
オブジェクト指向とは何ですか?
sumim
 
PDF
Introducao ao C#
Andre Teixeira Lopes
 
PPT
9. Input Output in java
Nilesh Dalvi
 
PPTX
Java servlets
yuvarani p
 
PDF
Advanced Production Debugging
Takipi
 
PDF
In Search of Segmentation
Adrian Cockcroft
 

More Related Content

What's hot(20)

PPTX
Clean code slide
Anh Huan Miu
 
PPTX
Dynamically Generate a CRUD Admin Panel with Java Annotations
Broadleaf Commerce
 
PPT
Oop java
Minal Maniar
 
PPTX
This keyword in java
Hitesh Kumar
 
PDF
#"button" data-testid="button" aria-checked="false" aria-label="Save #" role="switch" aria-haspopup="dialog" aria-controls=":R7klichr6:" popovertarget=":R7klichr6:">
Gustavo Zimmermann
 
PPTX
Clean code
Mahmoud Zizo
 
PPSX
Kotlin Language powerpoint show file
Saurabh Tripathi
 
PDF
Coding with golang
HannahMoss14
 
PDF
Programação Orientada a Objetos (POO) com PHP - Parte 1
Israel Messias
 
PPT
Abstract class in java
Lovely Professional University
 
PPTX
[OKKY 세미나] 정진욱 - 테스트하기 쉬운 코드로 개발하기
OKKY
 
PPSX
Elements of Java Language
Hitesh-Java
 
PDF
C# で Single Page Web アプリが開発できるフレームワーク&開発環境 「Blazor」 ― その概要と Web アプリ開発者にもたらす利点
Jun-ichi Sakamoto
 
PDF
Java modules
Rory Preddy
 
PPSX
Arrays in Java
Hitesh-Java
 
PPTX
JRE , JDK and platform independent nature of JAVA
Mehak Tawakley
 
PDF
オブジェクト指向とは何ですか?
sumim
 
PDF
Introducao ao C#
Andre Teixeira Lopes
 
PPT
9. Input Output in java
Nilesh Dalvi
 
PPTX
Java servlets
yuvarani p
 
Clean code slide
Anh Huan Miu
 
Dynamically Generate a CRUD Admin Panel with Java Annotations
Broadleaf Commerce
 
Oop java
Minal Maniar
 
This keyword in java
Hitesh Kumar
 
#"button" data-testid="button" aria-checked="false" aria-label="Save #" role="switch" aria-haspopup="dialog" aria-controls=":R5imichr6:" popovertarget=":R5imichr6:">
Gustavo Zimmermann
 
Clean code
Mahmoud Zizo
 
Kotlin Language powerpoint show file
Saurabh Tripathi
 
Coding with golang
HannahMoss14
 
Programação Orientada a Objetos (POO) com PHP - Parte 1
Israel Messias
 
Abstract class in java
Lovely Professional University
 
[OKKY 세미나] 정진욱 - 테스트하기 쉬운 코드로 개발하기
OKKY
 
Elements of Java Language
Hitesh-Java
 
C# で Single Page Web アプリが開発できるフレームワーク&開発環境 「Blazor」 ― その概要と Web アプリ開発者にもたらす利点
Jun-ichi Sakamoto
 
Java modules
Rory Preddy
 
Arrays in Java
Hitesh-Java
 
JRE , JDK and platform independent nature of JAVA
Mehak Tawakley
 
オブジェクト指向とは何ですか?
sumim
 
Introducao ao C#
Andre Teixeira Lopes
 
9. Input Output in java
Nilesh Dalvi
 
Java servlets
yuvarani p
 

Viewers also liked(15)

PDF
Advanced Production Debugging
Takipi
 
PDF
In Search of Segmentation
Adrian Cockcroft
 
PDF
Java 9: The (G1) GC Awakens!
Monica Beckwith
 
PDF
10 SQL Tricks that You Didn't Think Were Possible
Lukas Eder
 
PDF
Project Jigsaw in JDK 9: Modularity Comes To Java
C4Media
 
PDF
Scala Days NYC 2016
Martin Odersky
 
PPTX
Microservices + Oracle: A Bright Future
Kelly Goetsch
 
PPT
C#/.NET Little Wonders
BlackRabbitCoder
 
PPTX
More Little Wonders of C#/.NET
BlackRabbitCoder
 
PPT
Programming in c#
Shehrevar Davierwala
 
PPT
Java Notes
Abhishek Khune
 
PDF
Core java complete notes - Contact at +91-814-614-5674
Lokesh Kakkar Mobile No. 814-614-5674
 
PPT
Core java slides
Abhilash Nair
 
PPTX
Introduction to java
Veerabadra Badra
 
PDF
Alphorm.com support de la formation programmer en C# 6
Alphorm
 
Advanced Production Debugging
Takipi
 
In Search of Segmentation
Adrian Cockcroft
 
Java 9: The (G1) GC Awakens!
Monica Beckwith
 
10 SQL Tricks that You Didn't Think Were Possible
Lukas Eder
 
Project Jigsaw in JDK 9: Modularity Comes To Java
C4Media
 
Scala Days NYC 2016
Martin Odersky
 
Microservices + Oracle: A Bright Future
Kelly Goetsch
 
C#/.NET Little Wonders
BlackRabbitCoder
 
More Little Wonders of C#/.NET
BlackRabbitCoder
 
Programming in c#
Shehrevar Davierwala
 
Java Notes
Abhishek Khune
 
Core java complete notes - Contact at +91-814-614-5674
Lokesh Kakkar Mobile No. 814-614-5674
 
Core java slides
Abhilash Nair
 
Introduction to java
Veerabadra Badra
 
Alphorm.com support de la formation programmer en C# 6
Alphorm
 
Ad

Similar to Java SE 8 best practices(20)

PDF
Java 8 best practices - Stephen Colebourne
JAXLondon_Conference
 
PPTX
Java SE 8
Murali Pachiyappan
 
PPTX
Functional programming with_jdk8-s_ritter
Simon Ritter
 
PDF
Java 8 by example!
Mark Harrison
 
PDF
Java SE 8 library design
Stephen Colebourne
 
PDF
Lambda Functions in Java 8
Ganesh Samarthyam
 
PPTX
Functional Programming With Lambdas and Streams in JDK8
IndicThreads
 
PDF
Lambdas & Streams
C4Media
 
PPTX
Insight into java 1.8, OOP VS FP
Syed Awais Mazhar Bukhari
 
PPTX
Lambdas and-streams-s ritter-v3
Simon Ritter
 
PPTX
Java 8 new features
Aniket Thakur
 
PDF
Apouc 2014-java-8-create-the-future
OUGTH Oracle User Group in Thailand
 
PDF
FP in Java - Project Lambda and beyond
Mario Fusco
 
PDF
Introduction to new features in java 8
Raffi Khatchadourian
 
PDF
Functional programming in Java 8 - workshop at flatMap Oslo 2014
Fredrik Vraalsen
 
PPTX
Java 8 presentation
Van Huong
 
PDF
SeneJug java_8_prez_122015
senejug
 
PDF
Java 8 Workshop
Mario Fusco
 
PDF
Lambdas in Java 8
Tobias Coetzee
 
Java 8 best practices - Stephen Colebourne
JAXLondon_Conference
 
Functional programming with_jdk8-s_ritter
Simon Ritter
 
Java 8 by example!
Mark Harrison
 
Java SE 8 library design
Stephen Colebourne
 
Lambda Functions in Java 8
Ganesh Samarthyam
 
Functional Programming With Lambdas and Streams in JDK8
IndicThreads
 
Lambdas & Streams
C4Media
 
Insight into java 1.8, OOP VS FP
Syed Awais Mazhar Bukhari
 
Lambdas and-streams-s ritter-v3
Simon Ritter
 
Java 8 new features
Aniket Thakur
 
Apouc 2014-java-8-create-the-future
OUGTH Oracle User Group in Thailand
 
FP in Java - Project Lambda and beyond
Mario Fusco
 
Introduction to new features in java 8
Raffi Khatchadourian
 
Functional programming in Java 8 - workshop at flatMap Oslo 2014
Fredrik Vraalsen
 
Java 8 presentation
Van Huong
 
SeneJug java_8_prez_122015
senejug
 
Java 8 Workshop
Mario Fusco
 
Lambdas in Java 8
Tobias Coetzee
 
Ad

Recently uploaded(20)

PDF
Why is partnering with a SaaS development company crucial for enterprise succ...
Nextbrain Technologies
 
PDF
AOMEI Partition Assistant Crack 10.8.2 + WinPE Free Downlaod New Version 2025
bashirkhan333g
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PDF
Best Web development company in india 2025
Greenusys
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PDF
Simplify React app login with asgardeo-sdk
vaibhav289687
 
PPTX
Get Started with Maestro: Agent, Robot, and Human in Action – Session 5 of 5
klpathrudu
 
PPTX
Library_Management_System_PPT111111.pptx
nmtnissancrm
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
Dipole Tech Innovations – Global IT Solutions for Business Growth
dipoletechi3
 
PPTX
Smart Doctor Appointment Booking option in odoo.pptx
AxisTechnolabs
 
PDF
IObit Driver Booster Pro 12.4.0.585 Crack Free Download
henryc1122g
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PDF
UITP Summit Meep Pitch may 2025 MaaS Rebooted
campoamor1
 
PDF
ERP Consulting Services and Solutions by Contetra Pvt Ltd
jayjani123
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PDF
NPD Software -Omnex systems
omnex systems
 
Why is partnering with a SaaS development company crucial for enterprise succ...
Nextbrain Technologies
 
AOMEI Partition Assistant Crack 10.8.2 + WinPE Free Downlaod New Version 2025
bashirkhan333g
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
Best Web development company in india 2025
Greenusys
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Simplify React app login with asgardeo-sdk
vaibhav289687
 
Get Started with Maestro: Agent, Robot, and Human in Action – Session 5 of 5
klpathrudu
 
Library_Management_System_PPT111111.pptx
nmtnissancrm
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
Dipole Tech Innovations – Global IT Solutions for Business Growth
dipoletechi3
 
Smart Doctor Appointment Booking option in odoo.pptx
AxisTechnolabs
 
IObit Driver Booster Pro 12.4.0.585 Crack Free Download
henryc1122g
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
UITP Summit Meep Pitch may 2025 MaaS Rebooted
campoamor1
 
ERP Consulting Services and Solutions by Contetra Pvt Ltd
jayjani123
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
NPD Software -Omnex systems
omnex systems
 

Java SE 8 best practices

  • 1.Java SE 8 Best PracticesA personal viewpointStephen Colebourne, October 2015
  • 2.Agenda● ⇒ Introduction● λ Lambdas● f⒳ Functional interfaces● ! Exceptions● ? Optional● ♒ Streams● I Interfaces● Date and Time● Extras
  • 4.Introduction● What is a Best Practice?
  • 5.Introduction● What is a Best Practice?"commercial or professional proceduresthat are accepted or prescribed as beingcorrect or most effective"
  • 6.Introduction● What is the Best Practice for Java SE 8?
  • 7.Introduction● What is the Best Practice for Java SE 8?"whatever I say in the next 50 minutes"
  • 8.Introduction● Software Best Practice is mostly opinion● Different conclusions perfectly possible● My opinions are based on over a year using Java SE 8
  • 9.Introduction● Software Best Practice is mostly opinion● Different conclusions perfectly possible● My opinions are based on over a year using Java SE 8But you must exercise your own judgement!
  • 10.Java SE 8 version● Use Java SE 8 update 40 or later○ preferably use the latest available● Earlier versions have annoying lambda/javac issuesBestPractice
  • 12.Lambdas● Block of code○ like an anonymous inner class● Always assigned to a Functional Interface○ an interface with one abstract method● Uses target typing○ context determines type of the lambda
  • 13.Lambdas - Example// Java 7List<Person> people = loadPeople();Collections.sort(people, new Comparator<Person>() {@Overridepublic int compare(Person p1, Person p2) {return p1.name.compareTo(p2.name);}});
  • 14.Lambdas - Example// Java 7List<Person> people = loadPeople();Collections.sort(people, new Comparator<Person>() {@Overridepublic int compare(Person p1, Person p2) {return p1.name.compareTo(p2.name);}});
  • 15.Lambdas - Example// Java 8List<Person> people = loadPeople();Collections.sort(people,(Person p1, Person p2)p1.name.compareTo(p2.name));
  • 16.Lambdas - Example// Java 8List<Person> people = loadPeople();Collections.sort(people,(Person p1, Person p2) -> p1.name.compareTo(p2.name));
  • 17.Lambdas - Example// Java 8List<Person> people = loadPeople();Collections.sort(people,(Person p1, Person p2) -> p1.name.compareTo(p2.name));
  • 18.Lambdas - Example// Java 8List<Person> people = loadPeople();Collections.sort(people,(p1, p2) -> p1.name.compareTo(p2.name));
  • 19.Lambdas - Example// Java 8List<Person> people = loadPeople();people.sort((p1, p2) -> p1.name.compareTo(p2.name));
  • 20.Lambdas● Make use of parameter type inference● Only specify the types when compiler needs it// prefer(p1, p2) -> p1.name.compareTo(p2.name);// avoid(Person p1, Person p2) -> p1.name.compareTo(p2.name);BestPractice
  • 21.Lambdas● Do not use parameter brackets when optional// preferstr -> str.toUpperCase(Locale.US);// avoid(str) -> str.toUpperCase(Locale.US);BestPractice
  • 22.Lambdas● Do not declare local variables as 'final'● Use new "effectively final" conceptpublic UnaryOperator<String> upperCaser(Locale locale) {return str -> str.toUpperCase(locale);}BestPracticeDo not declare as 'final'
  • 23.Lambdas● Prefer expression lambdas over block lambdas● Use a separate method if necessary// preferstr -> str.toUpperCase(Locale.US);// use with carestr -> {return str.toUpperCase(Locale.US);}BestPractice
  • 24.Lambas for Abstraction● Two large methods contain same code● Except for one bit in the middle● Can use a lambda to express the difference
  • 25.Lambas for Abstractionprivate int doFoo() {// lots of code// logic specific to method1// lots of code}private int doBar() {// lots of code// logic specific to method2// lots of code}
  • 26.Lambas for Abstractionprivate int doFoo() {return doFooBar( lambdaOfFooSpecificLogic );}private int doFooBar(Function<A, B> fn) {// lots of coderesult = fn.apply(arg)// lots of code}BestPractice
  • 27.Example Abstractiondouble[][] res = new double[rowCount][colCount];for (int i = 0; i < rowCount; ++i) {for (int j = 0; j < colCount; ++j) {res[i][j] = pp.getCoefMatrix().get(i, j) * (nCoefs - j - 1);}}DoubleMatrix2D coef = new DoubleMatrix2D(res);
  • 28.Example AbstractionDoubleMatrix2D coef = DoubleMatrix2D.of(rowCount,colCount,(i, j) -> pp.getCoefMatrix().get(i, j) * (nCoefs - j - 1));// new methodpublic static DoubleMatrix2D of(int rows, int columns, IntIntToDoubleFunction valueFunction)
  • 30.Functional interfaces● An interface with a single abstract method○ Runnable○ Comparable○ Callable● Java SE 8 adds many new functional interfaces○ Function<T, R>○ Predicate<T>○ Supplier<T>○ Consumer<T>○ see java.util.function package
  • 31.Functional interfaces● Learn java.util.function package interface● Only write your own if extra semantics are valuable● If writing one, use @FunctionalInterface@FunctionalInterfacepublic interface FooBarQuery {public abstract Foo findAllFoos(Bar bar);}BestPractice
  • 32.Higher order methods● Methods accepting lambdas are nothing special○ declared type is just a normal interface● However there are some subtletiesprivate String nameGreet(Supplier<String> nameSupplier) {return "Hello " + nameSupplier.get();}// caller can use a lambdaString greeting = nameGreet(() -> "Bob");
  • 33.Avoid method overloads● Lambdas use target typing● Clashes with method overloading// avoidpublic class Foo<T> {public Foo<R> apply(Function<T, R> fn);public Foo<T> apply(UnaryOperator<T> fn);}
  • 34.Avoid method overloads● Lambdas use target typing● Clashes with method overloading● Use different method names to avoid clashesBestPractice// preferpublic class Foo<T> {public Foo<R> applyFunction(Function<T, R> fn);public Foo<T> applyOperator(UnaryOperator<T> fn);}
  • 35.Functional interface last● Prefer to have functional interface last○ when method takes mixture of FI and non-FI● Mostly stylistic○ slightly better IDE error recoveryBestPractice// preferpublic Foo parse(Locale locale, Function<Locale,Foo> fn);// avoidpublic Foo parse(Function<Locale,Foo> fn, Locale locale);
  • 37.Checked exceptions● Most functional interfaces do not declare exceptions● No simple way to put checked exceptions in lambdas// does not compile!public Function<String, Class> loader() {return className -> Class.forName(className);}Throws a checked exception
  • 38.Checked exceptions● Write or find a helper method● Converts checked exception to uncheckedpublic Function<String, Class> loader() {return Unchecked.function(className -> Class.forName(className));}BestPractice
  • 39.Checked exceptions● Helper methods can deal with any block of code○ convert to runtime exceptions● May be a good case for a block lambdaUnchecked.wrap(() -> {// any code that might throw a checked exception});
  • 40.Testing for exceptions● Complete unit tests often need to test for exceptionspublic void testConstructorRejectsEmptyString() {try {new FooBar("");fail();} catch (IllegalArgumentException ex) {// expected}}
  • 41.Testing for exceptions● Use a helper method● Lots of variations on this theme are possiblepublic void testConstructorRejectsEmptyString() {TestHelper.assertThrows(IllegalArgumentException.class, () -> new FooBar(""));}BestPractice
  • 44.Optional and null● New class 'Optional' added to Java 8● Polarizes opinions○ functional programming dudes think it is the saviour of the universe● Simple concept - two states○ present, with a value - Optional.of(foo)○ empty - Optional.empty()
  • 45.Optional and null● Standard code using null// library, returns null if not foundpublic Foo findFoo(String key) { … }// application codeFoo foo = findFoo(key);if (foo == null) {foo = Foo.DEFAULT; // or throw an exception}
  • 46.Optional and null● Standard code using Optional// library, returns null if not foundpublic Optional<Foo> findFoo(String key) { … }// application codeFoo foo = findFoo(key).orElse(Foo.DEFAULT);// orFoo foo = findFoo(key).orElseThrow(RuntimeException::new);
  • 47.Optional and null● Variable of type Optional must never be null● Never ever● Never, never, never, never!BestPractice
  • 48.Optional● Prefer "functional" methods like 'orElse()'● using 'isPresent()' a lot is misusing the featureBestPractice// preferFoo foo = findFoo(key).orElse(Foo.DEFAULT);// avoidOptional<Foo> optFoo = findFoo(key);if (optFoo.isPresent()) { … }
  • 49.Optional● Have a discussion and choose an approachA. Use everywhereB. Use instead of null on public APIs, input and outputC. Use instead of null on public return typesD. Use in a few selected placesE. Do not useBestPractice
  • 50.Optional● Have a discussion and choose an approachA. Use everywhereB. Use instead of null on public APIs, input and outputC. Use instead of null on public return types↖ my preferred choice ↗D. Use in a few selected placesE. Do not useBestPractice
  • 51.Optional● Optional is a class● Some memory/performance cost to using it● Not serializable● Not ideal to be an instance variable● JDK authors added it for return types● Use in parameters often annoying for callers● Use as return type gets best value from concepthttp://blog.joda.org/2015/08/java-se-8-optional-pragmatic-approach.html
  • 53.Streams● Most loops are the same● Repetitive design patterns● Stream library provides an abstraction● Lambdas used to pass the interesting bits
  • 54.StreamsList<Trade> trades = loadTrades();List<Money> valued = new ArrayList<Money>();for (Trade t : trades) {if (t.isActive()) {Money pv = presentValue(t);valued.add(pv);}}Loop to build outputlist from inputOnly interested insome tradesConverts each tradeto the money value
  • 55.StreamsList<Trade> trades = loadTrades();List<Money> valued = new ArrayList<Money>();for (Trade t : trades) {if (t.isActive()) {Money pv = presentValue(t);valued.add(pv);}}
  • 56.StreamsList<Trade> trades = loadTrades();List<Money> valued = new ArrayList<Money>();for (Trade t : trades) {if (t.isActive()) {Money pv = presentValue(t);valued.add(pv);}}
  • 57.StreamsList<Trade> trades = loadTrades();List<Money> valued = Listtradest.isActive()presentValue(t)
  • 58.StreamsList<Trade> trades = loadTrades();List<Money> valued = // List// trades// t.isActive()// presentValue(t)
  • 59.StreamsList<Trade> trades = loadTrades();List<Money> valued = // Listtrades.stream() // trades// t.isActive()// presentValue(t)
  • 60.StreamsList<Trade> trades = loadTrades();List<Money> valued = // Listtrades.stream() // trades.filter(t -> t.isActive()) // t.isActive()// presentValue(t)
  • 61.StreamsList<Trade> trades = loadTrades();List<Money> valued = // Listtrades.stream() // trades.filter(t -> t.isActive()) // t.isActive().map(t -> presentValue(t)) // presentValue(t)
  • 62.StreamsList<Trade> trades = loadTrades();List<Money> valued = // Listtrades.stream() // trades.filter(t -> t.isActive()) // t.isActive().map(t -> presentValue(t)) // presentValue(t).collect(Collectors.toList());
  • 63.StreamsList<Trade> trades = loadTrades();List<Money> valued =trades.stream().filter(t -> t.isActive()).map(t -> presentValue(t)).collect(Collectors.toList());
  • 64.Streams● Streams are great, sometimes● Important not to get carried away● Design focus was on Collections, not Maps● Key goal was simple parallelism
  • 65.StreamsList<Trade> trades = loadTrades();List<Money> valued =trades.stream().filter(t -> t.isActive()).map(t -> presentValue(t)).collect(Collectors.toList());
  • 66.StreamsList<Trade> trades = loadTrades();List<Money> valued =trades.parallelStream().filter(t -> t.isActive()).map(t -> presentValue(t)).collect(Collectors.toList());
  • 67.Streams● Do not overdo it● Stream not always more readable than loop● Good for Collections, less so for Maps● Don't obsess about method references○ IntelliJ hint may not be the best ideaBestPractice
  • 68.Streams● Benchmark use in performance critical sections● Parallel streams must be used with great care● Shared execution pool can be deceivingBestPractice
  • 69.StreamsList<Trade> trades = loadTrades();Predicate<Trade> activePredicate = t -> t.isActive();Function<Trade, Money> valueFn = t -> presentValue(t);List<Money> valued =trades.stream().filter(activePredicate).map(valueFn).collect(Collectors.toList());TopTip● Extract lines if struggling to get to compile
  • 70.StreamsList<Trade> trades = loadTrades();List<Money> valued =trades.stream().filter(t.isActive()).map((Trade t) -> presentValue(t)).collect(Collectors.toList());● Sometimes compiler needs a type hintTopTip
  • 71.Streams● Learn to love 'Collector' interface● Complex, but useful● Sometime necessary to write them● Need collectors for Guava 'ImmutableList' and friends○ see 'Guavate' class in OpenGamma Strata
  • 73.Interfaces● Now have super-powers● Default methods○ normal method, but on an interface● Static methods○ normal static method, but on an interface● Extend interfaces without breaking compatibility● Cannot default equals/hashCode/toString
  • 74.Interfaces● New macro-design options● Instead of factory class, use static method on interface● Instead of abstract class, use interface with defaults● Result tends to be fewer classes and better APITopTip
  • 75.Interfaces● If factory method is static on interface● And all API methods are on interface● Can implementation class be package scoped?BestPractice
  • 76.Coding Style● Use modifiers in interfaces● Much clearer now there are different types of method● Prepares for possible future with non-public methodsBestPracticepublic interface Foo {public static of(String key) { … }public abstract getKey();public default isActive() { … }}
  • 78.Date and Time● New Date and Time API - JSR 310● Covers dates, times, instants, periods, durations● Brings 80%+ of Joda-Time to the JDK● Fixes the mistakes in Joda-Time
  • 79.Date and TimeClass Date Time ZoneOffset ZoneId ExampleLocalDate ✔ ❌ ❌ ❌ 2015-12-03LocalTime ❌ ✔ ❌ ❌ 11:30LocalDateTime ✔ ✔ ❌ ❌ 2015-12-03T11:30OffsetDateTime ✔ ✔ ✔ ❌ 2015-12-03T11:30+01:00ZonedDateTime ✔ ✔ ✔ ✔ 2015-12-03T11:30+01:00[Europe/London]Instant ❌ ❌ ❌ ❌ 123456789 nanos from1970-01-01T00:00Z
  • 80.Date and Time● Move away from Joda-Time● Avoid java.util.Date and java.util.Calendar● Use ThreeTen-Extra project if necessary○ http://www.threeten.org/threeten-extra/● Focus on four most useful types○ LocalDate, LocalTime, ZonedDateTime, Instant● Network formats like XML/JSON use offset types○ OffsetTime, OffsetDateTimeBestPractice
  • 81.Date and Time● Temporal interfaces are low-level● Use concrete typesBestPractice// preferLocalDate date = LocalDate.of(2015, 10, 15);// avoidTemporal date = LocalDate.of(2015, 10, 15);
  • 83.Other features● Base64● Arithmetic without numeric overflow● Unsigned arithmetic● StampedLock● CompletableFuture● LongAdder/LongAccumulator● Enhanced control of OS processes
  • 84.Other Features● Enhanced annotations● Reflection on method parameters● No PermGen in Hotspot JVM● Nashorn JavaScript● JavaFX is finally ready to replace Swing
  • 85.Try a Java 8 open source library● JOOL○ https://github.com/jOOQ/jOOL● ThrowingLambdas○ https://github.com/fge/throwing-lambdas● Parts of OpenGamma Strata (strata-collect - Guavate)○ https://github.com/OpenGamma/Strata● But beware excessively functional ones○ most push ideas that don't really work well in Java
  • 86.Immutability● Favour immutable classes● Lambdas and streams prefer this● Preparation for value types (Java 10?)● Use Joda-Beans to generate immutable "beans"○ http://www.joda.org/joda-beans/
  • 88.Summary● Java 8 is great● Can be quite different to Java 7 and earlier● Vital to rethink coding style and standards○ methods on interfaces make a big difference● Beware the functional programming/Scala dudes○ a lot of their advice is simply not appropriate for Java

[8]ページ先頭

©2009-2025 Movatter.jp