SlideShare uma empresa Scribd logo
1 de 85
Katsconf – September 2016
garth.gilmour@instil.co
Put the Lime in the Coconut
• 10 Best Practices for Java 8
• 10 Sets of Best Practices for Java 8
About this talk…
I’ll Be Your Corporate Shill Today…
How Many Of You Are Using Java 8?
On With The Show!!!
1. General points about adopting Java 8
2. Using Lambdas and Method Refs
3. Coping with Functional Interfaces
4. Adding ‘Optional<T>’ into your codebase
5. The Streams API and Collections
6. Using Streams outside of collections
7. Functional programming with strings
8. Adding parallelism to streams
9. Simplifying Design Patterns with FP
10. The remainder of Java 8
Sets of Best Practises
Levels of Discussion
• High level principles
• Designing API’s
• Design in general
• Low level coding
• Pet peeves 
Its Been Amongst Us For Some Time…
Best Practises for Management
• You can’t avoid Java 8
• So plan for the pain of change…
• The future is (kinda) functional
• Your developers may already be
eager to embrace it 
• Explore other JVM languages
• Exploring != adopting
• Don’t accidentally encourage
use of anti-patterns in Java 8
* Or Clojure, Kotlin, Ceylon etc…
Lambdas and Method References
Replacing Anonymous Inner Classes
Expression Vs. Block Lambdas
Expression Vs. Block Lambdas
Expression Lambdas Good, Block Lambdas
Evil…
Best Practises for Lambdas and Method Refs
• obj::foo not x -> obj.foo(x)
• Only write lambdas which
have ‘obviously no errors’
• When in doubt prefer method
references to lambdas
• Don’t use block lambdas
• Eliminate superfluous syntax
• Including final on variables
which are ‘effectively final’
Functional Interfaces
Know Your Functional Interfaces
Overloading and Functional Interfaces
JavaDoc Guidelines for Functional Interfaces
Best Practises for Functional Interfaces
• Learn the functional interfaces
• Consider rewriting abstract
classes as functional
interfaces
• Avoid overloading with related
functional interfaces
• Only write your own functional
interfaces when unavoidable
• Follow the naming guidelines
when you write your own
• Use @FunctionalInterface
Optional
The Basics of Optional
The Basics of Optional
• optional.ifPresentOrElse(this::foo, this::bar)
• Optional<Account> opt = homeAcct(id).or(() -> workAcct(id))
• List<Email> emails = staff.stream()
.map(e -> e.getAddress())
.flatMap(Optional::stream)
.collect(toList())
New Optional Features in Java 9
//may not exist
Best Practises for Option
• Never return null from a
method in your public API
• Return an Option instead
• Consider whether to require
Option within your codebase
• Consider if Option as a
parameter is useful to you
• Never return null from a
method that declares Option
Be conservative in what you send, be
liberal in what you accept
Robustness Principle / Postel's Law
Feel the Evil…
Streams and Collections
Basic Use Of Streams
Basic Use Of Streams
Basic Use Of Streams
Basic Use Of Streams
Two Ways to Find the Average
NB I do know about ‘IntStream.average’ and ‘Collectors.averagingInt’ etc…
Don’t Go Fully Functional in Java
Best Practises for Streams and Collections Pt1
• Be judicious in your use of the
‘functional toolkit’
• The methods of the toolkit
are patterns of iteration
• Not every use of iteration
cleanly fits the pattern
• Don’t obsess about local state
• Its global state that’s bad
Why Are Streams Read-Once?
• Streams are typically explained like UNIX pipes
• Each call creates a temporary result which is passed on
• The reality is somewhat different
• A stream pipeline is made up of a source, zero or more
intermediate operations and a terminal operation
• The terminal operations typically:
• Produce an aggregate value (e.g. reduce and collect)
• Select a particular item (e.g. findAny and findFirst)
• Iterate over the items (forEach)
• The operations you specify produce a stream description
• This description is executed at the terminal operation
• Each stage of the pipeline has a set of flags
• These can be used to take shortcuts
Understand How Streams Work Internally
The ‘Spliterator’ Interface
The ‘Spliterator’ Interface
Best Practises for Streams and Collections Pt2
• Its good to return streams
from the methods of your API
• Items can be fetched lazily
• The ‘toolkit’ is right there
• Regular collections are
easy to build from streams
• But not in every case
• Typically when the data
source might change
Using Collectors
Best Practises for Streams and Collections Pt3
• Understand how streams
(may) work ‘under the hood’
• Fetching may be lazy
• Actions will be postponed
till the termination
• Shorts-cuts can be taken
• Write code in ‘sympathy’
• In particular become
familiar with Collectors
Streams and Boxing
Streams and Boxing
Streams and Boxing
Without: 1066 With: 2041 Difference: 975
Without: 833 With: 1328 Difference: 495
Without: 833 With: 1330 Difference: 497
Without: 851 With: 1291 Difference: 440
Without: 830 With: 1322 Difference: 492
Without: 862 With: 1365 Difference: 503
Without: 874 With: 1249 Difference: 375
Without: 840 With: 1259 Difference: 419
…
Without: 851 With: 1239 Difference: 388
Without: 830 With: 1253 Difference: 423
Without: 843 With: 1231 Difference: 388
Without: 825 With: 1232 Difference: 407
Without: 835 With: 1260 Difference: 425
Without: 837 With: 1244 Difference: 407
Without: 841 With: 1244 Difference: 403
Average difference is: 419.96
Then I Showed This To David…
Streams and Boxing
Streams and Boxing
Streams and Boxing
Streams and Boxing
NB: Units are operations per second so bigger is better 
Best Practises for Streams and Collections Pt4
• Be aware of the overhead of
boxing when using types such
as ‘Stream<Double>’
• Use the specialized types
like ‘DoubleStream’ instead
Functional Programming With Strings
Examples of FP With Strings in Other Languages
class Program {
static void Main(string[] args) {
string input = " abc-def#ghi+jkl ";
string output = RemovePunctuation(input);
Console.WriteLine(output);
}
private static string RemovePunctuation(string input) {
var letters = from c in input.ToLower()
where c >= 'a' && c <= 'z'
select c;
return new string(letters.ToArray());
}
}
abcdefghijkl
Manipulating Strings Using the Streams API
‘String.chars’ returns an ‘IntStream’
Best Practises for Strings
• Avoid combining the Streams
API with String objects
Streams Outside Collections
Using Streams with Zip Files
Using Streams with Zip Files
Using Streams with ‘BufferedReader’
Using Streams with ‘BufferedReader’
Best Practises for Streams and Types
• Remember streams are for
more than collections
• Keep an eye as JSE libraries
and open source projects
incrementally add support
• Reactive Streams are coming
in Java 9   
Parallel Streams
Be Warned!
Some people, when confronted
with a problem, think "I know, I’ll
use multi-threading". Nothhw tpe
yawrve o oblems.
Basic Parallel Streams
Returning to our Benchmark
Returning to our Benchmark
NB: Units are operations per second so bigger is better 
Its Not That Easy
A More Complex Problem
A More Complex Problem
NB: Units are operations per second so bigger is better 
Its Still Not That Easy
Converting the Code to REST
Sequential
(GET /lines)
Parallel
(GET /linesParallel)
1 Thread 100 Requests 24 9
100 Threads 20 Requests 825 775
200 Threads 20 Requests 2086 2103
300 Threads 20 Requests 3598 3487
Average Times Via JMeter (Smaller is Better)
Its Still Still Not That Easy
Doug Lea et al…
http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html
Best Practises for Parallel Streams
• Parallel isn’t a panacea
• Parallel isn’t a panacea
• Parallel isn’t a panacea
• ParParallelallel isn’tn’tn’t
aaaaaaaaaaaa panacea
• Use it when the data and
task have the right ‘shape’
• Test correctly to confirm
there is real world benefit
Testing Your Parallel Collections
OO Design Patterns and FP
• Patterns are fixes for issues in some style of programming
• Places where the toolkit provided by your language is weak
• Both OO and FP languages have associated patterns
• The OO and FP styles of programming compliment one another
• The use of one can remove the need for a pattern in the other
• We have already seen an example
• The ‘Optional’ type replaces the ‘Null Object’ Pattern
• Having lambdas reduces the need for ‘objects as tasks’
• For example in the Command Pattern we can have a table of
lambdas instead of a table of instances of anonymous types
OO Design Patterns and FP
Best Practises for Design Patterns
• Look again at your design
and its use of patterns
• Could these be reduced
or removed via FP?
• Pay particular attention
were objects model tasks
• Command
• Observer
• Strategy
• Visitor
The Other Stuff
Best Practises for Other Features
• Annotations can be repeated!
• Refactor away ugliness
• Use the new Date/Time API
• JodaTime is now legacy
• Be aware that annotations
can appear just about
anywhere
• Benchmarking?
• Code generation?
• Prepare for modules in Java 9
Thanks for Watching 

Mais conteúdo relacionado

Mais procurados

Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsNewCircle Training
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsEmiel Paasschens
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8Knoldus Inc.
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8icarter09
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8LivePerson
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
java 8 new features
java 8 new features java 8 new features
java 8 new features Rohit Verma
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in JavaMudit Gupta
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Ganesh Samarthyam
 

Mais procurados (20)

Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Java8
Java8Java8
Java8
 
Java 8 by example!
Java 8 by example!Java 8 by example!
Java 8 by example!
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in Java
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
 

Semelhante a 10 Sets of Best Practices for Java 8

Lambda Expressions Java 8 Features usage
Lambda Expressions  Java 8 Features usageLambda Expressions  Java 8 Features usage
Lambda Expressions Java 8 Features usageAsmaShaikh478737
 
Java Closures
Java ClosuresJava Closures
Java ClosuresBen Evans
 
Learning from "Effective Scala"
Learning from "Effective Scala"Learning from "Effective Scala"
Learning from "Effective Scala"Kazuhiro Sera
 
C++ Introduction brown bag
C++ Introduction brown bagC++ Introduction brown bag
C++ Introduction brown bagJacob Green
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscriptBill Buchan
 
Optimising code using Span<T>
Optimising code using Span<T>Optimising code using Span<T>
Optimising code using Span<T>Mirco Vanini
 
Scala Bay Meetup - The state of Scala code style and quality
Scala Bay Meetup - The state of Scala code style and qualityScala Bay Meetup - The state of Scala code style and quality
Scala Bay Meetup - The state of Scala code style and qualityJaime Jorge
 
Beginning Java for .NET developers
Beginning Java for .NET developersBeginning Java for .NET developers
Beginning Java for .NET developersAndrei Rinea
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C LanguageMohamed Elsayed
 
JSR 335 / java 8 - update reference
JSR 335 / java 8 - update referenceJSR 335 / java 8 - update reference
JSR 335 / java 8 - update referencesandeepji_choudhary
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and ClassesMichael Heron
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptxQ-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptxnyomans1
 
Q-SPractical_introduction_to_Python.pptx
Q-SPractical_introduction_to_Python.pptxQ-SPractical_introduction_to_Python.pptx
Q-SPractical_introduction_to_Python.pptxJeromeTacata3
 
introduction to server-side scripting
introduction to server-side scriptingintroduction to server-side scripting
introduction to server-side scriptingAmirul Shafeeq
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 

Semelhante a 10 Sets of Best Practices for Java 8 (20)

Lambda Expressions Java 8 Features usage
Lambda Expressions  Java 8 Features usageLambda Expressions  Java 8 Features usage
Lambda Expressions Java 8 Features usage
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
2CPP02 - C++ Primer
2CPP02 - C++ Primer2CPP02 - C++ Primer
2CPP02 - C++ Primer
 
Java Closures
Java ClosuresJava Closures
Java Closures
 
Learning from "Effective Scala"
Learning from "Effective Scala"Learning from "Effective Scala"
Learning from "Effective Scala"
 
C++ Introduction brown bag
C++ Introduction brown bagC++ Introduction brown bag
C++ Introduction brown bag
 
2014 java functional
2014 java functional2014 java functional
2014 java functional
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscript
 
Optimising code using Span<T>
Optimising code using Span<T>Optimising code using Span<T>
Optimising code using Span<T>
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
Scala Bay Meetup - The state of Scala code style and quality
Scala Bay Meetup - The state of Scala code style and qualityScala Bay Meetup - The state of Scala code style and quality
Scala Bay Meetup - The state of Scala code style and quality
 
Beginning Java for .NET developers
Beginning Java for .NET developersBeginning Java for .NET developers
Beginning Java for .NET developers
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C Language
 
JSR 335 / java 8 - update reference
JSR 335 / java 8 - update referenceJSR 335 / java 8 - update reference
JSR 335 / java 8 - update reference
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptxQ-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptx
 
Q-SPractical_introduction_to_Python.pptx
Q-SPractical_introduction_to_Python.pptxQ-SPractical_introduction_to_Python.pptx
Q-SPractical_introduction_to_Python.pptx
 
introduction to server-side scripting
introduction to server-side scriptingintroduction to server-side scripting
introduction to server-side scripting
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 

Mais de Garth Gilmour

Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android UpdateGarth Gilmour
 
TypeScript Vs. KotlinJS
TypeScript Vs. KotlinJSTypeScript Vs. KotlinJS
TypeScript Vs. KotlinJSGarth Gilmour
 
Shut Up And Eat Your Veg
Shut Up And Eat Your VegShut Up And Eat Your Veg
Shut Up And Eat Your VegGarth Gilmour
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerGarth Gilmour
 
A TypeScript Fans KotlinJS Adventures
A TypeScript Fans KotlinJS AdventuresA TypeScript Fans KotlinJS Adventures
A TypeScript Fans KotlinJS AdventuresGarth Gilmour
 
The Heat Death Of Enterprise IT
The Heat Death Of Enterprise ITThe Heat Death Of Enterprise IT
The Heat Death Of Enterprise ITGarth Gilmour
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerGarth Gilmour
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScriptGarth Gilmour
 
Generics On The JVM (What you don't know will hurt you)
Generics On The JVM (What you don't know will hurt you)Generics On The JVM (What you don't know will hurt you)
Generics On The JVM (What you don't know will hurt you)Garth Gilmour
 
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
Using Kotlin, to Create Kotlin,to Teach Kotlin,in SpaceUsing Kotlin, to Create Kotlin,to Teach Kotlin,in Space
Using Kotlin, to Create Kotlin, to Teach Kotlin, in SpaceGarth Gilmour
 
Is Software Engineering A Profession?
Is Software Engineering A Profession?Is Software Engineering A Profession?
Is Software Engineering A Profession?Garth Gilmour
 
Social Distancing is not Behaving Distantly
Social Distancing is not Behaving DistantlySocial Distancing is not Behaving Distantly
Social Distancing is not Behaving DistantlyGarth Gilmour
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala MakeoverGarth Gilmour
 
Transitioning Android Teams Into Kotlin
Transitioning Android Teams Into KotlinTransitioning Android Teams Into Kotlin
Transitioning Android Teams Into KotlinGarth Gilmour
 
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)Garth Gilmour
 
The Three Horse Race
The Three Horse RaceThe Three Horse Race
The Three Horse RaceGarth Gilmour
 
The Bestiary of Pure Functional Programming
The Bestiary of Pure Functional Programming The Bestiary of Pure Functional Programming
The Bestiary of Pure Functional Programming Garth Gilmour
 
BelTech 2019 Presenters Workshop
BelTech 2019 Presenters WorkshopBelTech 2019 Presenters Workshop
BelTech 2019 Presenters WorkshopGarth Gilmour
 
Kotlin The Whole Damn Family
Kotlin The Whole Damn FamilyKotlin The Whole Damn Family
Kotlin The Whole Damn FamilyGarth Gilmour
 

Mais de Garth Gilmour (20)

Compose in Theory
Compose in TheoryCompose in Theory
Compose in Theory
 
Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android Update
 
TypeScript Vs. KotlinJS
TypeScript Vs. KotlinJSTypeScript Vs. KotlinJS
TypeScript Vs. KotlinJS
 
Shut Up And Eat Your Veg
Shut Up And Eat Your VegShut Up And Eat Your Veg
Shut Up And Eat Your Veg
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
 
A TypeScript Fans KotlinJS Adventures
A TypeScript Fans KotlinJS AdventuresA TypeScript Fans KotlinJS Adventures
A TypeScript Fans KotlinJS Adventures
 
The Heat Death Of Enterprise IT
The Heat Death Of Enterprise ITThe Heat Death Of Enterprise IT
The Heat Death Of Enterprise IT
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
Generics On The JVM (What you don't know will hurt you)
Generics On The JVM (What you don't know will hurt you)Generics On The JVM (What you don't know will hurt you)
Generics On The JVM (What you don't know will hurt you)
 
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
Using Kotlin, to Create Kotlin,to Teach Kotlin,in SpaceUsing Kotlin, to Create Kotlin,to Teach Kotlin,in Space
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
 
Is Software Engineering A Profession?
Is Software Engineering A Profession?Is Software Engineering A Profession?
Is Software Engineering A Profession?
 
Social Distancing is not Behaving Distantly
Social Distancing is not Behaving DistantlySocial Distancing is not Behaving Distantly
Social Distancing is not Behaving Distantly
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
 
Transitioning Android Teams Into Kotlin
Transitioning Android Teams Into KotlinTransitioning Android Teams Into Kotlin
Transitioning Android Teams Into Kotlin
 
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
 
The Three Horse Race
The Three Horse RaceThe Three Horse Race
The Three Horse Race
 
The Bestiary of Pure Functional Programming
The Bestiary of Pure Functional Programming The Bestiary of Pure Functional Programming
The Bestiary of Pure Functional Programming
 
BelTech 2019 Presenters Workshop
BelTech 2019 Presenters WorkshopBelTech 2019 Presenters Workshop
BelTech 2019 Presenters Workshop
 
Kotlin The Whole Damn Family
Kotlin The Whole Damn FamilyKotlin The Whole Damn Family
Kotlin The Whole Damn Family
 

Último

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
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
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
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
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
 
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
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
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
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
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
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
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
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
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
 

Último (20)

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-...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
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
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
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
 
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
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
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
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
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
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
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...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
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
 

10 Sets of Best Practices for Java 8

  • 1. Katsconf – September 2016 garth.gilmour@instil.co Put the Lime in the Coconut • 10 Best Practices for Java 8 • 10 Sets of Best Practices for Java 8
  • 3. I’ll Be Your Corporate Shill Today…
  • 4. How Many Of You Are Using Java 8?
  • 5. On With The Show!!!
  • 6. 1. General points about adopting Java 8 2. Using Lambdas and Method Refs 3. Coping with Functional Interfaces 4. Adding ‘Optional<T>’ into your codebase 5. The Streams API and Collections 6. Using Streams outside of collections 7. Functional programming with strings 8. Adding parallelism to streams 9. Simplifying Design Patterns with FP 10. The remainder of Java 8 Sets of Best Practises
  • 7. Levels of Discussion • High level principles • Designing API’s • Design in general • Low level coding • Pet peeves 
  • 8. Its Been Amongst Us For Some Time…
  • 9. Best Practises for Management • You can’t avoid Java 8 • So plan for the pain of change… • The future is (kinda) functional • Your developers may already be eager to embrace it  • Explore other JVM languages • Exploring != adopting • Don’t accidentally encourage use of anti-patterns in Java 8
  • 10. * Or Clojure, Kotlin, Ceylon etc…
  • 11. Lambdas and Method References
  • 15. Expression Lambdas Good, Block Lambdas Evil…
  • 16. Best Practises for Lambdas and Method Refs • obj::foo not x -> obj.foo(x) • Only write lambdas which have ‘obviously no errors’ • When in doubt prefer method references to lambdas • Don’t use block lambdas • Eliminate superfluous syntax • Including final on variables which are ‘effectively final’
  • 18. Know Your Functional Interfaces
  • 20. JavaDoc Guidelines for Functional Interfaces
  • 21. Best Practises for Functional Interfaces • Learn the functional interfaces • Consider rewriting abstract classes as functional interfaces • Avoid overloading with related functional interfaces • Only write your own functional interfaces when unavoidable • Follow the naming guidelines when you write your own • Use @FunctionalInterface
  • 23. The Basics of Optional
  • 24. The Basics of Optional
  • 25. • optional.ifPresentOrElse(this::foo, this::bar) • Optional<Account> opt = homeAcct(id).or(() -> workAcct(id)) • List<Email> emails = staff.stream() .map(e -> e.getAddress()) .flatMap(Optional::stream) .collect(toList()) New Optional Features in Java 9 //may not exist
  • 26. Best Practises for Option • Never return null from a method in your public API • Return an Option instead • Consider whether to require Option within your codebase • Consider if Option as a parameter is useful to you • Never return null from a method that declares Option Be conservative in what you send, be liberal in what you accept Robustness Principle / Postel's Law
  • 29. Basic Use Of Streams
  • 30. Basic Use Of Streams
  • 31. Basic Use Of Streams
  • 32. Basic Use Of Streams
  • 33. Two Ways to Find the Average NB I do know about ‘IntStream.average’ and ‘Collectors.averagingInt’ etc…
  • 34. Don’t Go Fully Functional in Java
  • 35. Best Practises for Streams and Collections Pt1 • Be judicious in your use of the ‘functional toolkit’ • The methods of the toolkit are patterns of iteration • Not every use of iteration cleanly fits the pattern • Don’t obsess about local state • Its global state that’s bad
  • 36. Why Are Streams Read-Once?
  • 37. • Streams are typically explained like UNIX pipes • Each call creates a temporary result which is passed on • The reality is somewhat different • A stream pipeline is made up of a source, zero or more intermediate operations and a terminal operation • The terminal operations typically: • Produce an aggregate value (e.g. reduce and collect) • Select a particular item (e.g. findAny and findFirst) • Iterate over the items (forEach) • The operations you specify produce a stream description • This description is executed at the terminal operation • Each stage of the pipeline has a set of flags • These can be used to take shortcuts Understand How Streams Work Internally
  • 40. Best Practises for Streams and Collections Pt2 • Its good to return streams from the methods of your API • Items can be fetched lazily • The ‘toolkit’ is right there • Regular collections are easy to build from streams • But not in every case • Typically when the data source might change
  • 42.
  • 43. Best Practises for Streams and Collections Pt3 • Understand how streams (may) work ‘under the hood’ • Fetching may be lazy • Actions will be postponed till the termination • Shorts-cuts can be taken • Write code in ‘sympathy’ • In particular become familiar with Collectors
  • 46. Streams and Boxing Without: 1066 With: 2041 Difference: 975 Without: 833 With: 1328 Difference: 495 Without: 833 With: 1330 Difference: 497 Without: 851 With: 1291 Difference: 440 Without: 830 With: 1322 Difference: 492 Without: 862 With: 1365 Difference: 503 Without: 874 With: 1249 Difference: 375 Without: 840 With: 1259 Difference: 419 … Without: 851 With: 1239 Difference: 388 Without: 830 With: 1253 Difference: 423 Without: 843 With: 1231 Difference: 388 Without: 825 With: 1232 Difference: 407 Without: 835 With: 1260 Difference: 425 Without: 837 With: 1244 Difference: 407 Without: 841 With: 1244 Difference: 403 Average difference is: 419.96
  • 47. Then I Showed This To David…
  • 51. Streams and Boxing NB: Units are operations per second so bigger is better 
  • 52. Best Practises for Streams and Collections Pt4 • Be aware of the overhead of boxing when using types such as ‘Stream<Double>’ • Use the specialized types like ‘DoubleStream’ instead
  • 54. Examples of FP With Strings in Other Languages class Program { static void Main(string[] args) { string input = " abc-def#ghi+jkl "; string output = RemovePunctuation(input); Console.WriteLine(output); } private static string RemovePunctuation(string input) { var letters = from c in input.ToLower() where c >= 'a' && c <= 'z' select c; return new string(letters.ToArray()); } } abcdefghijkl
  • 55. Manipulating Strings Using the Streams API
  • 56.
  • 57. ‘String.chars’ returns an ‘IntStream’
  • 58. Best Practises for Strings • Avoid combining the Streams API with String objects
  • 60. Using Streams with Zip Files
  • 61. Using Streams with Zip Files
  • 62. Using Streams with ‘BufferedReader’
  • 63. Using Streams with ‘BufferedReader’
  • 64. Best Practises for Streams and Types • Remember streams are for more than collections • Keep an eye as JSE libraries and open source projects incrementally add support • Reactive Streams are coming in Java 9   
  • 66. Be Warned! Some people, when confronted with a problem, think "I know, I’ll use multi-threading". Nothhw tpe yawrve o oblems.
  • 68. Returning to our Benchmark
  • 69. Returning to our Benchmark NB: Units are operations per second so bigger is better 
  • 70. Its Not That Easy
  • 71. A More Complex Problem
  • 72. A More Complex Problem NB: Units are operations per second so bigger is better 
  • 73. Its Still Not That Easy
  • 75. Sequential (GET /lines) Parallel (GET /linesParallel) 1 Thread 100 Requests 24 9 100 Threads 20 Requests 825 775 200 Threads 20 Requests 2086 2103 300 Threads 20 Requests 3598 3487 Average Times Via JMeter (Smaller is Better)
  • 76. Its Still Still Not That Easy
  • 77. Doug Lea et al… http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html
  • 78. Best Practises for Parallel Streams • Parallel isn’t a panacea • Parallel isn’t a panacea • Parallel isn’t a panacea • ParParallelallel isn’tn’tn’t aaaaaaaaaaaa panacea • Use it when the data and task have the right ‘shape’ • Test correctly to confirm there is real world benefit
  • 79. Testing Your Parallel Collections
  • 81. • Patterns are fixes for issues in some style of programming • Places where the toolkit provided by your language is weak • Both OO and FP languages have associated patterns • The OO and FP styles of programming compliment one another • The use of one can remove the need for a pattern in the other • We have already seen an example • The ‘Optional’ type replaces the ‘Null Object’ Pattern • Having lambdas reduces the need for ‘objects as tasks’ • For example in the Command Pattern we can have a table of lambdas instead of a table of instances of anonymous types OO Design Patterns and FP
  • 82. Best Practises for Design Patterns • Look again at your design and its use of patterns • Could these be reduced or removed via FP? • Pay particular attention were objects model tasks • Command • Observer • Strategy • Visitor
  • 84. Best Practises for Other Features • Annotations can be repeated! • Refactor away ugliness • Use the new Date/Time API • JodaTime is now legacy • Be aware that annotations can appear just about anywhere • Benchmarking? • Code generation? • Prepare for modules in Java 9