SlideShare a Scribd company logo
1 of 88
Download to read offline
Java SE 8 Best Practices
A personal viewpoint
Stephen 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 procedures
that are accepted or prescribed as being
correct 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 8
But 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 issues
Best
Practice
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 7
List<Person> people = loadPeople();
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.name.compareTo(p2.name);
}
});
Lambdas - Example
// Java 7
List<Person> people = loadPeople();
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.name.compareTo(p2.name);
}
});
Lambdas - Example
// Java 8
List<Person> people = loadPeople();
Collections.sort(people,
(Person p1, Person p2)
p1.name.compareTo(p2.name)
);
Lambdas - Example
// Java 8
List<Person> people = loadPeople();
Collections.sort(people,
(Person p1, Person p2) -> p1.name.compareTo(p2.name));
Lambdas - Example
// Java 8
List<Person> people = loadPeople();
Collections.sort(people,
(Person p1, Person p2) -> p1.name.compareTo(p2.name));
Lambdas - Example
// Java 8
List<Person> people = loadPeople();
Collections.sort(people,
(p1, p2) -> p1.name.compareTo(p2.name));
Lambdas - Example
// Java 8
List<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);
Best
Practice
Lambdas
● Do not use parameter brackets when optional
// prefer
str -> str.toUpperCase(Locale.US);
// avoid
(str) -> str.toUpperCase(Locale.US);
Best
Practice
Lambdas
● Do not declare local variables as 'final'
● Use new "effectively final" concept
public UnaryOperator<String> upperCaser(Locale locale) {
return str -> str.toUpperCase(locale);
}
Best
Practice
Do not declare as 'final'
Lambdas
● Prefer expression lambdas over block lambdas
● Use a separate method if necessary
// prefer
str -> str.toUpperCase(Locale.US);
// use with care
str -> {
return str.toUpperCase(Locale.US);
}
Best
Practice
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 Abstraction
private 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 Abstraction
private int doFoo() {
return doFooBar( lambdaOfFooSpecificLogic );
}
private int doFooBar(Function<A, B> fn) {
// lots of code
result = fn.apply(arg)
// lots of code
}
Best
Practice
Example Abstraction
double[][] 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 Abstraction
DoubleMatrix2D coef = DoubleMatrix2D.of(
rowCount,
colCount,
(i, j) -> pp.getCoefMatrix().get(i, j) * (nCoefs - j - 1));
// new method
public static DoubleMatrix2D of(
int rows, int columns, IntIntToDoubleFunction valueFunction)
Functional interfaces
fβ’³
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
@FunctionalInterface
public interface FooBarQuery {
public abstract Foo findAllFoos(Bar bar);
}
Best
Practice
Higher order methods
● Methods accepting lambdas are nothing special
β—‹ declared type is just a normal interface
● However there are some subtleties
private String nameGreet(Supplier<String> nameSupplier) {
return "Hello " + nameSupplier.get();
}
// caller can use a lambda
String greeting = nameGreet(() -> "Bob");
Avoid method overloads
● Lambdas use target typing
● Clashes with method overloading
// avoid
public 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 clashes
Best
Practice
// prefer
public 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 recovery
Best
Practice
// prefer
public Foo parse(Locale locale, Function<Locale,Foo> fn);
// avoid
public 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 unchecked
public Function<String, Class> loader() {
return Unchecked.function(
className -> Class.forName(className));
}
Best
Practice
Checked exceptions
● Helper methods can deal with any block of code
β—‹ convert to runtime exceptions
● May be a good case for a block lambda
Unchecked.wrap(() -> {
// any code that might throw a checked exception
});
Testing for exceptions
● Complete unit tests often need to test for exceptions
public void testConstructorRejectsEmptyString() {
try {
new FooBar("");
fail();
} catch (IllegalArgumentException ex) {
// expected
}
}
Testing for exceptions
● Use a helper method
● Lots of variations on this theme are possible
public void testConstructorRejectsEmptyString() {
TestHelper.assertThrows(
IllegalArgumentException.class, () -> new FooBar(""));
}
Best
Practice
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 found
public Foo findFoo(String key) { … }
// application code
Foo 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 found
public Optional<Foo> findFoo(String key) { … }
// application code
Foo foo = findFoo(key).orElse(Foo.DEFAULT);
// or
Foo foo = findFoo(key).orElseThrow(RuntimeException::new);
Optional and null
● Variable of type Optional must never be null
● Never ever
● Never, never, never, never!
Best
Practice
Optional
● Prefer "functional" methods like 'orElse()'
● using 'isPresent()' a lot is misusing the feature
Best
Practice
// prefer
Foo foo = findFoo(key).orElse(Foo.DEFAULT);
// avoid
Optional<Foo> optFoo = findFoo(key);
if (optFoo.isPresent()) { … }
Optional
● Have a discussion and choose an approach
A. Use everywhere
B. Use instead of null on public APIs, input and output
C. Use instead of null on public return types
D. Use in a few selected places
E. Do not use
Best
Practice
Optional
● Have a discussion and choose an approach
A. Use everywhere
B. Use instead of null on public APIs, input and output
C. Use instead of null on public return types
β†– my preferred choice β†—
D. Use in a few selected places
E. Do not use
Best
Practice
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 concept
http://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
Streams
List<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 output
list from input
Only interested in
some trades
Converts each trade
to the money value
Streams
List<Trade> trades = loadTrades();
List<Money> valued = new ArrayList<Money>();
for (Trade t : trades) {
if (t.isActive()) {
Money pv = presentValue(t);
valued.add(pv);
}
}
Streams
List<Trade> trades = loadTrades();
List<Money> valued = new ArrayList<Money>();
for (Trade t : trades) {
if (t.isActive()) {
Money pv = presentValue(t);
valued.add(pv);
}
}
Streams
List<Trade> trades = loadTrades();
List<Money> valued = List
trades
t.isActive()
presentValue(t)
Streams
List<Trade> trades = loadTrades();
List<Money> valued = // List
// trades
// t.isActive()
// presentValue(t)
Streams
List<Trade> trades = loadTrades();
List<Money> valued = // List
trades.stream() // trades
// t.isActive()
// presentValue(t)
Streams
List<Trade> trades = loadTrades();
List<Money> valued = // List
trades.stream() // trades
.filter(t -> t.isActive()) // t.isActive()
// presentValue(t)
Streams
List<Trade> trades = loadTrades();
List<Money> valued = // List
trades.stream() // trades
.filter(t -> t.isActive()) // t.isActive()
.map(t -> presentValue(t)) // presentValue(t)
Streams
List<Trade> trades = loadTrades();
List<Money> valued = // List
trades.stream() // trades
.filter(t -> t.isActive()) // t.isActive()
.map(t -> presentValue(t)) // presentValue(t)
.collect(Collectors.toList());
Streams
List<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
Streams
List<Trade> trades = loadTrades();
List<Money> valued =
trades.stream()
.filter(t -> t.isActive())
.map(t -> presentValue(t))
.collect(Collectors.toList());
Streams
List<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 idea
Best
Practice
Streams
● Benchmark use in performance critical sections
● Parallel streams must be used with great care
● Shared execution pool can be deceiving
Best
Practice
Streams
List<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());
Top
Tip
● Extract lines if struggling to get to compile
Streams
List<Trade> trades = loadTrades();
List<Money> valued =
trades.stream()
.filter(t.isActive())
.map((Trade t) -> presentValue(t))
.collect(Collectors.toList());
● Sometimes compiler needs a type hint
Top
Tip
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
Interfaces
I
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 API
Top
Tip
Interfaces
● If factory method is static on interface
● And all API methods are on interface
● Can implementation class be package scoped?
Best
Practice
Coding Style
● Use modifiers in interfaces
● Much clearer now there are different types of method
● Prepares for possible future with non-public methods
Best
Practice
public 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 Time
Class Date Time ZoneOffset ZoneId Example
LocalDate βœ” ❌ ❌ ❌ 2015-12-03
LocalTime ❌ βœ” ❌ ❌ 11:30
LocalDateTime βœ” βœ” ❌ ❌ 2015-12-03T11:30
OffsetDateTime βœ” βœ” βœ” ❌ 2015-12-03T11:30+01:00
ZonedDateTime βœ” βœ” βœ” βœ” 2015-12-03T11:30+01:00
[Europe/London]
Instant ❌ ❌ ❌ ❌ 123456789 nanos from
1970-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, OffsetDateTime
Best
Practice
Date and Time
● Temporal interfaces are low-level
● Use concrete types
Best
Practice
// prefer
LocalDate date = LocalDate.of(2015, 10, 15);
// avoid
Temporal 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/
Summary
J8
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

More Related Content

What's hot

Best practices in Java
Best practices in JavaBest practices in Java
Best practices in JavaMudit Gupta
Β 
Curso de ReactJS
Curso de ReactJSCurso de ReactJS
Curso de ReactJSGustavo Lopes
Β 
Tips about hibernate with spring data jpa
Tips about hibernate with spring data jpaTips about hibernate with spring data jpa
Tips about hibernate with spring data jpaThiago Dos Santos Hora
Β 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for javamaheshm1206
Β 
Introdução ao Spring Framework
Introdução ao Spring FrameworkIntrodução ao Spring Framework
Introdução ao Spring FrameworkNatanael Fonseca
Β 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep DiveGabriel Walt
Β 
Programação Orientação a Objetos - Herança
Programação Orientação a Objetos - HerançaProgramação Orientação a Objetos - Herança
Programação Orientação a Objetos - HerançaDaniel Brandão
Β 
Modern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafModern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafLAY Leangsros
Β 
JavaScript From Hell - CONFidence 2.0 2009
JavaScript From Hell - CONFidence 2.0 2009JavaScript From Hell - CONFidence 2.0 2009
JavaScript From Hell - CONFidence 2.0 2009Mario Heiderich
Β 
Documenting your REST API with Swagger - JOIN 2014
Documenting your REST API with Swagger - JOIN 2014Documenting your REST API with Swagger - JOIN 2014
Documenting your REST API with Swagger - JOIN 2014JWORKS powered by Ordina
Β 
Coding standards
Coding standardsCoding standards
Coding standardsMark Reynolds
Β 
RESTful API 섀계
RESTful API 섀계RESTful API 섀계
RESTful API 섀계Jinho Yoo
Β 

What's hot (20)

Clean code
Clean codeClean code
Clean code
Β 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in Java
Β 
Curso de ReactJS
Curso de ReactJSCurso de ReactJS
Curso de ReactJS
Β 
Spring boot
Spring bootSpring boot
Spring boot
Β 
Spring security
Spring securitySpring security
Spring security
Β 
Tips about hibernate with spring data jpa
Tips about hibernate with spring data jpaTips about hibernate with spring data jpa
Tips about hibernate with spring data jpa
Β 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
Β 
Introdução ao Spring Framework
Introdução ao Spring FrameworkIntrodução ao Spring Framework
Introdução ao Spring Framework
Β 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep Dive
Β 
Go lang
Go langGo lang
Go lang
Β 
Programação Orientação a Objetos - Herança
Programação Orientação a Objetos - HerançaProgramação Orientação a Objetos - Herança
Programação Orientação a Objetos - Herança
Β 
Modern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafModern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and Thymeleaf
Β 
JavaScript From Hell - CONFidence 2.0 2009
JavaScript From Hell - CONFidence 2.0 2009JavaScript From Hell - CONFidence 2.0 2009
JavaScript From Hell - CONFidence 2.0 2009
Β 
Documenting your REST API with Swagger - JOIN 2014
Documenting your REST API with Swagger - JOIN 2014Documenting your REST API with Swagger - JOIN 2014
Documenting your REST API with Swagger - JOIN 2014
Β 
Spring ioc
Spring iocSpring ioc
Spring ioc
Β 
Sightly - Part 2
Sightly - Part 2Sightly - Part 2
Sightly - Part 2
Β 
Complete Java Course
Complete Java CourseComplete Java Course
Complete Java Course
Β 
Coding standards
Coding standardsCoding standards
Coding standards
Β 
RESTful API 섀계
RESTful API 섀계RESTful API 섀계
RESTful API 섀계
Β 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
Β 

Viewers also liked

Advanced Production Debugging
Advanced Production DebuggingAdvanced Production Debugging
Advanced Production DebuggingTakipi
Β 
In Search of Segmentation
In Search of SegmentationIn Search of Segmentation
In Search of SegmentationAdrian Cockcroft
Β 
Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!Monica Beckwith
Β 
10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were Possible10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were PossibleLukas Eder
Β 
Project Jigsaw in JDK 9: Modularity Comes To Java
Project Jigsaw in JDK 9: Modularity Comes To JavaProject Jigsaw in JDK 9: Modularity Comes To Java
Project Jigsaw in JDK 9: Modularity Comes To JavaC4Media
Β 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016Martin Odersky
Β 
Microservices + Oracle: A Bright Future
Microservices + Oracle: A Bright FutureMicroservices + Oracle: A Bright Future
Microservices + Oracle: A Bright FutureKelly Goetsch
Β 
C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little WondersBlackRabbitCoder
Β 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NETMore Little Wonders of C#/.NET
More Little Wonders of C#/.NETBlackRabbitCoder
Β 
Core java slides
Core java slidesCore java slides
Core java slidesAbhilash Nair
Β 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaVeerabadra Badra
Β 
Alphorm.com support de la formation programmer en C# 6
Alphorm.com support de la formation programmer en C# 6Alphorm.com support de la formation programmer en C# 6
Alphorm.com support de la formation programmer en C# 6Alphorm
Β 

Viewers also liked (15)

Advanced Production Debugging
Advanced Production DebuggingAdvanced Production Debugging
Advanced Production Debugging
Β 
In Search of Segmentation
In Search of SegmentationIn Search of Segmentation
In Search of Segmentation
Β 
Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!
Β 
10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were Possible10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were Possible
Β 
Project Jigsaw in JDK 9: Modularity Comes To Java
Project Jigsaw in JDK 9: Modularity Comes To JavaProject Jigsaw in JDK 9: Modularity Comes To Java
Project Jigsaw in JDK 9: Modularity Comes To Java
Β 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016
Β 
Microservices + Oracle: A Bright Future
Microservices + Oracle: A Bright FutureMicroservices + Oracle: A Bright Future
Microservices + Oracle: A Bright Future
Β 
C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little Wonders
Β 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NETMore Little Wonders of C#/.NET
More Little Wonders of C#/.NET
Β 
Programming in c#
Programming in c#Programming in c#
Programming in c#
Β 
Java Notes
Java NotesJava Notes
Java Notes
Β 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
Β 
Core java slides
Core java slidesCore java slides
Core java slides
Β 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Β 
Alphorm.com support de la formation programmer en C# 6
Alphorm.com support de la formation programmer en C# 6Alphorm.com support de la formation programmer en C# 6
Alphorm.com support de la formation programmer en C# 6
Β 

Similar to Java SE 8 best practices

java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxBruceLee275640
Β 
Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018Mark Niebergall
Β 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
Β 
Java For Automation
Java   For AutomationJava   For Automation
Java For AutomationAbhijeet Dubey
Β 
Advanced PHP Simplified
Advanced PHP SimplifiedAdvanced PHP Simplified
Advanced PHP SimplifiedMark Niebergall
Β 
Android Open source coading guidel ine
Android Open source coading guidel ineAndroid Open source coading guidel ine
Android Open source coading guidel inePragati Singh
Β 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)David McCarter
Β 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
Β 
Java 7 & 8 New Features
Java 7 & 8 New FeaturesJava 7 & 8 New Features
Java 7 & 8 New FeaturesLeandro Coutinho
Β 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhHarmeet Singh(Taara)
Β 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to javaSadhanaParameswaran
Β 
Apache Dispatch
Apache DispatchApache Dispatch
Apache DispatchFred Moyer
Β 
Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Javahendersk
Β 
Intro to java 8
Intro to java 8Intro to java 8
Intro to java 8John Godoi
Β 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8Tobias Coetzee
Β 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For SyntaxPravinYalameli
Β 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in javaElizabeth alexander
Β 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonCodemotion
Β 

Similar to Java SE 8 best practices (20)

java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
Β 
Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018
Β 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Β 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
Β 
Advanced PHP Simplified
Advanced PHP SimplifiedAdvanced PHP Simplified
Advanced PHP Simplified
Β 
Android Open source coading guidel ine
Android Open source coading guidel ineAndroid Open source coading guidel ine
Android Open source coading guidel ine
Β 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Β 
Core java
Core javaCore java
Core java
Β 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
Β 
Java conventions
Java conventionsJava conventions
Java conventions
Β 
Java 7 & 8 New Features
Java 7 & 8 New FeaturesJava 7 & 8 New Features
Java 7 & 8 New Features
Β 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singh
Β 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to java
Β 
Apache Dispatch
Apache DispatchApache Dispatch
Apache Dispatch
Β 
Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Java
Β 
Intro to java 8
Intro to java 8Intro to java 8
Intro to java 8
Β 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
Β 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
Β 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
Β 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
Β 

More from Stephen Colebourne

Java SE 9 modules - an introduction (July 2018)
Java SE 9 modules - an introduction (July 2018)Java SE 9 modules - an introduction (July 2018)
Java SE 9 modules - an introduction (July 2018)Stephen Colebourne
Β 
Amber and beyond: Java language changes
Amber and beyond: Java language changesAmber and beyond: Java language changes
Amber and beyond: Java language changesStephen Colebourne
Β 
Java SE 9 modules (JPMS) - an introduction
Java SE 9 modules (JPMS) - an introductionJava SE 9 modules (JPMS) - an introduction
Java SE 9 modules (JPMS) - an introductionStephen Colebourne
Β 
Strata, Open Source Market Risk
Strata, Open Source Market RiskStrata, Open Source Market Risk
Strata, Open Source Market RiskStephen Colebourne
Β 
Java SE 8 library design
Java SE 8 library designJava SE 8 library design
Java SE 8 library designStephen Colebourne
Β 
Code generating beans in Java
Code generating beans in JavaCode generating beans in Java
Code generating beans in JavaStephen Colebourne
Β 

More from Stephen Colebourne (6)

Java SE 9 modules - an introduction (July 2018)
Java SE 9 modules - an introduction (July 2018)Java SE 9 modules - an introduction (July 2018)
Java SE 9 modules - an introduction (July 2018)
Β 
Amber and beyond: Java language changes
Amber and beyond: Java language changesAmber and beyond: Java language changes
Amber and beyond: Java language changes
Β 
Java SE 9 modules (JPMS) - an introduction
Java SE 9 modules (JPMS) - an introductionJava SE 9 modules (JPMS) - an introduction
Java SE 9 modules (JPMS) - an introduction
Β 
Strata, Open Source Market Risk
Strata, Open Source Market RiskStrata, Open Source Market Risk
Strata, Open Source Market Risk
Β 
Java SE 8 library design
Java SE 8 library designJava SE 8 library design
Java SE 8 library design
Β 
Code generating beans in Java
Code generating beans in JavaCode generating beans in Java
Code generating beans in Java
Β 

Recently uploaded

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
Β 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
Β 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
Β 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
Β 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
Β 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
Β 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
Β 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
Β 
CHEAP Call Girls in Pushp Vihar (-DELHI )πŸ” 9953056974πŸ”(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )πŸ” 9953056974πŸ”(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )πŸ” 9953056974πŸ”(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )πŸ” 9953056974πŸ”(=)/CALL GIRLS SERVICE9953056974 Low Rate Call Girls In Saket, Delhi NCR
Β 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
Β 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
Β 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
Β 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
Β 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
Β 
(Genuine) Escort Service Lucknow | Starting β‚Ή,5K To @25k with A/C πŸ§‘πŸ½β€β€οΈβ€πŸ§‘πŸ» 89...
(Genuine) Escort Service Lucknow | Starting β‚Ή,5K To @25k with A/C πŸ§‘πŸ½β€β€οΈβ€πŸ§‘πŸ» 89...(Genuine) Escort Service Lucknow | Starting β‚Ή,5K To @25k with A/C πŸ§‘πŸ½β€β€οΈβ€πŸ§‘πŸ» 89...
(Genuine) Escort Service Lucknow | Starting β‚Ή,5K To @25k with A/C πŸ§‘πŸ½β€β€οΈβ€πŸ§‘πŸ» 89...gurkirankumar98700
Β 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
Β 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
Β 
Shapes for Sharing between Graph Data SpacesΒ - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data SpacesΒ - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data SpacesΒ - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data SpacesΒ - and Epistemic Querying of RDF-...Steffen Staab
Β 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
Β 

Recently uploaded (20)

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
Β 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
Β 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
Β 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
Β 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
Β 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Β 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
Β 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
Β 
CHEAP Call Girls in Pushp Vihar (-DELHI )πŸ” 9953056974πŸ”(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )πŸ” 9953056974πŸ”(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )πŸ” 9953056974πŸ”(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )πŸ” 9953056974πŸ”(=)/CALL GIRLS SERVICE
Β 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Β 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
Β 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Β 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
Β 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
Β 
(Genuine) Escort Service Lucknow | Starting β‚Ή,5K To @25k with A/C πŸ§‘πŸ½β€β€οΈβ€πŸ§‘πŸ» 89...
(Genuine) Escort Service Lucknow | Starting β‚Ή,5K To @25k with A/C πŸ§‘πŸ½β€β€οΈβ€πŸ§‘πŸ» 89...(Genuine) Escort Service Lucknow | Starting β‚Ή,5K To @25k with A/C πŸ§‘πŸ½β€β€οΈβ€πŸ§‘πŸ» 89...
(Genuine) Escort Service Lucknow | Starting β‚Ή,5K To @25k with A/C πŸ§‘πŸ½β€β€οΈβ€πŸ§‘πŸ» 89...
Β 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
Β 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
Β 
Shapes for Sharing between Graph Data SpacesΒ - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data SpacesΒ - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data SpacesΒ - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data SpacesΒ - and Epistemic Querying of RDF-...
Β 
Call Girls In Mukherjee Nagar πŸ“± 9999965857 🀩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar πŸ“±  9999965857  🀩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar πŸ“±  9999965857  🀩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar πŸ“± 9999965857 🀩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Β 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Β 

Java SE 8 best practices

  • 1. Java SE 8 Best Practices A personal viewpoint Stephen 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 procedures that are accepted or prescribed as being correct 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 8 But 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 issues Best Practice
  • 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 7 List<Person> people = loadPeople(); Collections.sort(people, new Comparator<Person>() { @Override public int compare(Person p1, Person p2) { return p1.name.compareTo(p2.name); } });
  • 14. Lambdas - Example // Java 7 List<Person> people = loadPeople(); Collections.sort(people, new Comparator<Person>() { @Override public int compare(Person p1, Person p2) { return p1.name.compareTo(p2.name); } });
  • 15. Lambdas - Example // Java 8 List<Person> people = loadPeople(); Collections.sort(people, (Person p1, Person p2) p1.name.compareTo(p2.name) );
  • 16. Lambdas - Example // Java 8 List<Person> people = loadPeople(); Collections.sort(people, (Person p1, Person p2) -> p1.name.compareTo(p2.name));
  • 17. Lambdas - Example // Java 8 List<Person> people = loadPeople(); Collections.sort(people, (Person p1, Person p2) -> p1.name.compareTo(p2.name));
  • 18. Lambdas - Example // Java 8 List<Person> people = loadPeople(); Collections.sort(people, (p1, p2) -> p1.name.compareTo(p2.name));
  • 19. Lambdas - Example // Java 8 List<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); Best Practice
  • 21. Lambdas ● Do not use parameter brackets when optional // prefer str -> str.toUpperCase(Locale.US); // avoid (str) -> str.toUpperCase(Locale.US); Best Practice
  • 22. Lambdas ● Do not declare local variables as 'final' ● Use new "effectively final" concept public UnaryOperator<String> upperCaser(Locale locale) { return str -> str.toUpperCase(locale); } Best Practice Do not declare as 'final'
  • 23. Lambdas ● Prefer expression lambdas over block lambdas ● Use a separate method if necessary // prefer str -> str.toUpperCase(Locale.US); // use with care str -> { return str.toUpperCase(Locale.US); } Best Practice
  • 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 Abstraction private 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 Abstraction private int doFoo() { return doFooBar( lambdaOfFooSpecificLogic ); } private int doFooBar(Function<A, B> fn) { // lots of code result = fn.apply(arg) // lots of code } Best Practice
  • 27. Example Abstraction double[][] 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 Abstraction DoubleMatrix2D coef = DoubleMatrix2D.of( rowCount, colCount, (i, j) -> pp.getCoefMatrix().get(i, j) * (nCoefs - j - 1)); // new method public 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 @FunctionalInterface public interface FooBarQuery { public abstract Foo findAllFoos(Bar bar); } Best Practice
  • 32. Higher order methods ● Methods accepting lambdas are nothing special β—‹ declared type is just a normal interface ● However there are some subtleties private String nameGreet(Supplier<String> nameSupplier) { return "Hello " + nameSupplier.get(); } // caller can use a lambda String greeting = nameGreet(() -> "Bob");
  • 33. Avoid method overloads ● Lambdas use target typing ● Clashes with method overloading // avoid public 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 clashes Best Practice // prefer public 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 recovery Best Practice // prefer public Foo parse(Locale locale, Function<Locale,Foo> fn); // avoid public 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 unchecked public Function<String, Class> loader() { return Unchecked.function( className -> Class.forName(className)); } Best Practice
  • 39. Checked exceptions ● Helper methods can deal with any block of code β—‹ convert to runtime exceptions ● May be a good case for a block lambda Unchecked.wrap(() -> { // any code that might throw a checked exception });
  • 40. Testing for exceptions ● Complete unit tests often need to test for exceptions public 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 possible public void testConstructorRejectsEmptyString() { TestHelper.assertThrows( IllegalArgumentException.class, () -> new FooBar("")); } Best Practice
  • 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 found public Foo findFoo(String key) { … } // application code Foo 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 found public Optional<Foo> findFoo(String key) { … } // application code Foo foo = findFoo(key).orElse(Foo.DEFAULT); // or Foo foo = findFoo(key).orElseThrow(RuntimeException::new);
  • 47. Optional and null ● Variable of type Optional must never be null ● Never ever ● Never, never, never, never! Best Practice
  • 48. Optional ● Prefer "functional" methods like 'orElse()' ● using 'isPresent()' a lot is misusing the feature Best Practice // prefer Foo foo = findFoo(key).orElse(Foo.DEFAULT); // avoid Optional<Foo> optFoo = findFoo(key); if (optFoo.isPresent()) { … }
  • 49. Optional ● Have a discussion and choose an approach A. Use everywhere B. Use instead of null on public APIs, input and output C. Use instead of null on public return types D. Use in a few selected places E. Do not use Best Practice
  • 50. Optional ● Have a discussion and choose an approach A. Use everywhere B. Use instead of null on public APIs, input and output C. Use instead of null on public return types β†– my preferred choice β†— D. Use in a few selected places E. Do not use Best Practice
  • 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 concept http://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. Streams List<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 output list from input Only interested in some trades Converts each trade to the money value
  • 55. Streams List<Trade> trades = loadTrades(); List<Money> valued = new ArrayList<Money>(); for (Trade t : trades) { if (t.isActive()) { Money pv = presentValue(t); valued.add(pv); } }
  • 56. Streams List<Trade> trades = loadTrades(); List<Money> valued = new ArrayList<Money>(); for (Trade t : trades) { if (t.isActive()) { Money pv = presentValue(t); valued.add(pv); } }
  • 57. Streams List<Trade> trades = loadTrades(); List<Money> valued = List trades t.isActive() presentValue(t)
  • 58. Streams List<Trade> trades = loadTrades(); List<Money> valued = // List // trades // t.isActive() // presentValue(t)
  • 59. Streams List<Trade> trades = loadTrades(); List<Money> valued = // List trades.stream() // trades // t.isActive() // presentValue(t)
  • 60. Streams List<Trade> trades = loadTrades(); List<Money> valued = // List trades.stream() // trades .filter(t -> t.isActive()) // t.isActive() // presentValue(t)
  • 61. Streams List<Trade> trades = loadTrades(); List<Money> valued = // List trades.stream() // trades .filter(t -> t.isActive()) // t.isActive() .map(t -> presentValue(t)) // presentValue(t)
  • 62. Streams List<Trade> trades = loadTrades(); List<Money> valued = // List trades.stream() // trades .filter(t -> t.isActive()) // t.isActive() .map(t -> presentValue(t)) // presentValue(t) .collect(Collectors.toList());
  • 63. Streams List<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. Streams List<Trade> trades = loadTrades(); List<Money> valued = trades.stream() .filter(t -> t.isActive()) .map(t -> presentValue(t)) .collect(Collectors.toList());
  • 66. Streams List<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 idea Best Practice
  • 68. Streams ● Benchmark use in performance critical sections ● Parallel streams must be used with great care ● Shared execution pool can be deceiving Best Practice
  • 69. Streams List<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()); Top Tip ● Extract lines if struggling to get to compile
  • 70. Streams List<Trade> trades = loadTrades(); List<Money> valued = trades.stream() .filter(t.isActive()) .map((Trade t) -> presentValue(t)) .collect(Collectors.toList()); ● Sometimes compiler needs a type hint Top Tip
  • 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 API Top Tip
  • 75. Interfaces ● If factory method is static on interface ● And all API methods are on interface ● Can implementation class be package scoped? Best Practice
  • 76. Coding Style ● Use modifiers in interfaces ● Much clearer now there are different types of method ● Prepares for possible future with non-public methods Best Practice public 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 Time Class Date Time ZoneOffset ZoneId Example LocalDate βœ” ❌ ❌ ❌ 2015-12-03 LocalTime ❌ βœ” ❌ ❌ 11:30 LocalDateTime βœ” βœ” ❌ ❌ 2015-12-03T11:30 OffsetDateTime βœ” βœ” βœ” ❌ 2015-12-03T11:30+01:00 ZonedDateTime βœ” βœ” βœ” βœ” 2015-12-03T11:30+01:00 [Europe/London] Instant ❌ ❌ ❌ ❌ 123456789 nanos from 1970-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, OffsetDateTime Best Practice
  • 81. Date and Time ● Temporal interfaces are low-level ● Use concrete types Best Practice // prefer LocalDate date = LocalDate.of(2015, 10, 15); // avoid Temporal 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