SlideShare a Scribd company logo
@mirocupak
Miro Cupak
VP Engineering, DNAstack
01/06/2018
Writing clean code
with Java 9+
@mirocupak
Clarity, simplicity, brevity, humanity
!2
http://www.osnews.com/story/19266/WTFs_m https://xkcd.com/1695/
https://theamericanscholar.org/writing-english-as-a-second-language/
@mirocupak !3
https://www.amazon.ca/Clean-Code-Handbook-Software-
Craftsmanship/dp/0132350882/
https://www.amazon.ca/Effective-Java-3rd-Joshua-Bloch/dp/
0134685997/
@mirocupak
Features
!4
• Factory methods for collections.
• Improved try-with-resources.
• Private methods in interfaces.
• Stream API enhancements.
• Extensions to Optional.
• HTTP/2 client.
• Type inference.
@mirocupak !5
Factory methods for
collections
@mirocupak
Factory methods for collections
!6
• Obtain immutable collections via of/ofEntries methods.
• Create immutable copies of collections via copyOf (Java 10).
• Static import java.util.Map.entry.
• Less verbose, no static initializer blocks.
• Don’t use Arrays.asList or Stream.of as shortcuts for creating
collections.
• Don’t use external libraries if you only need immutable collections
(Guava).
• No need to worry about leaving references to underlying collections.
• Thread-safe and can be shared freely (no need for defensive copies).
• Good performance.
• Don’t create mutable collections unless necessary.
@mirocupak !7
Improved try-with-resources
@mirocupak
Improved try-with-resources
!8
• Always prefer try-with-resources, don’t use try-finally and definitely
don’t use finalizers to close resources.
• Be aware of convenience methods, such as
InputStream.transferTo.
• Don’t create unnecessary helper objects.
@mirocupak !9
Private methods in
interfaces
@mirocupak
Private methods in interfaces
!10
• Default methods, like all other methods, should be short.
• DRY.
• Use private methods to keep default methods short.
• Use private methods to extract shared core of default methods.
• Use default methods for providing standard implementations for new
interface code.
• Don’t use default methods to extend existing interfaces unless
necessary.
@mirocupak !11
Stream API enhancements
@mirocupak
Stream API enhancements
!12
• Be aware of new stream methods: takeWhile, dropWhile,
iterate.
• Prefer collecting into immutable collections using
toUnmodifiableList, toUnmodifiableSet,
toUnmodifiableMap.
• Check for convenience stream methods before converting to streams
manually (e.g. Matcher, LocalDate).
• Avoid unnecessary null checks with ofNullable.
• Streams are suitable for more use cases now, but not all use cases.
• Don’t overuse streams as they can make code hard to read and
difficult to maintain.
@mirocupak !13
Extensions to Optional
@mirocupak
Extensions to Optional
!14
• Use ifPresentOrElse instead of if-isPresent construct.
• or provides a clean fluent way of chaining behaviour on Optionals.
• Be aware of orElse* methods, e.g. the new orElseThrow (Java 10).
• Use stream to take advantage of the lazy nature of streams and
handle streams of Optionals.
• Remember that isPresent is rarely the answer.
@mirocupak !15
HTTP/2 client
@mirocupak
HTTP/2 client
!16
• Clean separation: HttpClient, HttpRequest, HttpResponse.
• HttpURLConnection is not pleasant to use.
• Avoid APIs with side effects.
• The new client API is versatile, flexible and clean.
• Prefer functionality in the JDK to external libraries.
• But aware it’s an incubator module.
@mirocupak !17
Type inference
@mirocupak
Diamond operator with anonymous classes
!18
• Use <> for anonymous classes, like everywhere else.
• <> improves readability and consistency.
• Use anonymous classes only when needed (e.g. abstract classes,
interfaces with multiple abstract methods…), otherwise replace with
lambdas.
@mirocupak
Local variable type inference
!19
• Does not replace static typing.
• Generally good.
• Reduces boilerplate and improves readability.
• Helps with maintenance and refactoring.
• Use for local variables with initializers (especially constructors) and for
loops.
• Can’t use for method formals, constructor formals, method return types,
fields, catch formals, null or array initializers, lambdas, method references,
or any other kind of variable declaration.
• Consider whether to use when the generated type is not obvious.
• But use for complex types when breaking chained or nested expressions
with local variables.
• Primitive types might surprise you, be careful (e.g. byte, short, long all
inferred as int).
@mirocupak
Local variable type inference
!20
• Be very careful about combining with <> and generic methods (e.g. var
list = new ArrayList<>()).
• Probably not the best idea to use with anonymous classes.
• Use carefully chosen and expressive variable names.
• Don’t use Hungarian notation.
• Don’t rely on IDEs.
• Minimize the scope of local variables.
• Declare variable when it’s first used.
• Declaration not containing an initializer (i.e. you can’t use var) often
indicates the scope is not minimal.
• Prefer for loops to while loops.
• Keep methods small and focused.
• Code to the interface pattern does not work, but that’s kind of OK.
@mirocupak
Questions?
!21
More info:
Session notes on Twitter.
Blog: https://mirocupak.com/

More Related Content

PDF
Writing clean code with modern Java
PDF
Writing clean code with modern Java
PDF
Writing clean code with Java in 2018
PDF
Master class in modern Java
PDF
Master class in modern Java
PDF
Master class in Java in 2018
PDF
Clean code with Java 9
PDF
The good, the bad, and the ugly of Java API design
Writing clean code with modern Java
Writing clean code with modern Java
Writing clean code with Java in 2018
Master class in modern Java
Master class in modern Java
Master class in Java in 2018
Clean code with Java 9
The good, the bad, and the ugly of Java API design

Similar to Voxxed Athens 2018 - Clean Code with Java9+ (20)

PDF
Working With Concurrency In Java 8
PDF
The good, the bad, and the ugly of Java API design
PDF
The good, the bad, and the ugly of Java API design
PPTX
Reading Notes : the practice of programming
PDF
Ajaxworld07
PDF
Ajaxworld07
KEY
25 Real Life Tips In Ruby on Rails Development
PDF
The Good, the Bad and the Ugly things to do with android
PDF
The good, the bad, and the ugly of Java API design
PDF
The Good, the Bad and the Ugly of Java API design
PPTX
Writing code for others
PPT
openmp.New.intro-unc.edu.ppt
PDF
2024 DAPUG Conference Arnaud Bouchez Technical Debt
PDF
Writing Readable Code
PPTX
10 Sets of Best Practices for Java 8
PDF
Scala Bay Meetup - The state of Scala code style and quality
PPTX
Javascript best practices
KEY
Learning from "Effective Scala"
PDF
The ES6 Conundrum - All Things Open 2015
PDF
(6) c sharp introduction_advanced_features_part_i
Working With Concurrency In Java 8
The good, the bad, and the ugly of Java API design
The good, the bad, and the ugly of Java API design
Reading Notes : the practice of programming
Ajaxworld07
Ajaxworld07
25 Real Life Tips In Ruby on Rails Development
The Good, the Bad and the Ugly things to do with android
The good, the bad, and the ugly of Java API design
The Good, the Bad and the Ugly of Java API design
Writing code for others
openmp.New.intro-unc.edu.ppt
2024 DAPUG Conference Arnaud Bouchez Technical Debt
Writing Readable Code
10 Sets of Best Practices for Java 8
Scala Bay Meetup - The state of Scala code style and quality
Javascript best practices
Learning from "Effective Scala"
The ES6 Conundrum - All Things Open 2015
(6) c sharp introduction_advanced_features_part_i
Ad

More from Voxxed Athens (18)

PPTX
Voxxed Athens 2018 - Eventing, Serverless, and the Extensible Enterprise
PDF
Voxxed Athens 2018 - Let’s Get Chatty with Conversational Interface with Java...
PPTX
Voxxed Athens 2018 - IBM Watson Machine Learning – Build and train AI models ...
PDF
Voxxed Athens 2018 - We're going to talk about no sql, you can't join
PDF
Voxxed Athens 2018 - Methods and Practices for Guaranteed Failure in Big Data
PDF
Voxxed Athens 2018 - The secret for high quality software: Listen to your people
PDF
Voxxed Athens 2018 - A scalable maritime platform providing services through...
PDF
Voxxed Athens 2018 - UX design and back-ends: When the back-end meets the user
PDF
Voxxed Athens 2018 - Your Local Meet-up: Your Path to Crafts(wo)manship
PDF
Voxxed Athens 2018 - The quantum computers are coming
PDF
Voxxed Athens 2018 - Serverless by Design
PDF
Voxxed Athens 2018 - Getting real with progressive web apps in 2018
PDF
Voxxed Athens 2018 - Why Kotlin?
PDF
Voxxed Athens 2018 - Java EE is dead Long live jakarta EE!
PDF
Voxxed Athens 2018 - How WebAssembly is changing the Web and what it means to...
PDF
Voxxed Athens 2018 - Going agile with kanban
PDF
Voxxed Athens 2018 - Elasticsearch (R)Evolution — You Know, for Search...
PDF
Voxxed Athens 2018 - Graph databases & data integration
Voxxed Athens 2018 - Eventing, Serverless, and the Extensible Enterprise
Voxxed Athens 2018 - Let’s Get Chatty with Conversational Interface with Java...
Voxxed Athens 2018 - IBM Watson Machine Learning – Build and train AI models ...
Voxxed Athens 2018 - We're going to talk about no sql, you can't join
Voxxed Athens 2018 - Methods and Practices for Guaranteed Failure in Big Data
Voxxed Athens 2018 - The secret for high quality software: Listen to your people
Voxxed Athens 2018 - A scalable maritime platform providing services through...
Voxxed Athens 2018 - UX design and back-ends: When the back-end meets the user
Voxxed Athens 2018 - Your Local Meet-up: Your Path to Crafts(wo)manship
Voxxed Athens 2018 - The quantum computers are coming
Voxxed Athens 2018 - Serverless by Design
Voxxed Athens 2018 - Getting real with progressive web apps in 2018
Voxxed Athens 2018 - Why Kotlin?
Voxxed Athens 2018 - Java EE is dead Long live jakarta EE!
Voxxed Athens 2018 - How WebAssembly is changing the Web and what it means to...
Voxxed Athens 2018 - Going agile with kanban
Voxxed Athens 2018 - Elasticsearch (R)Evolution — You Know, for Search...
Voxxed Athens 2018 - Graph databases & data integration
Ad

Recently uploaded (20)

PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPT
Teaching material agriculture food technology
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Spectroscopy.pptx food analysis technology
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
KodekX | Application Modernization Development
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Big Data Technologies - Introduction.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Encapsulation theory and applications.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
Reach Out and Touch Someone: Haptics and Empathic Computing
Teaching material agriculture food technology
Building Integrated photovoltaic BIPV_UPV.pdf
Spectroscopy.pptx food analysis technology
Spectral efficient network and resource selection model in 5G networks
KodekX | Application Modernization Development
Review of recent advances in non-invasive hemoglobin estimation
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
NewMind AI Weekly Chronicles - August'25 Week I
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Big Data Technologies - Introduction.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Encapsulation theory and applications.pdf
Machine learning based COVID-19 study performance prediction
Per capita expenditure prediction using model stacking based on satellite ima...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
20250228 LYD VKU AI Blended-Learning.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Dropbox Q2 2025 Financial Results & Investor Presentation

Voxxed Athens 2018 - Clean Code with Java9+

  • 1. @mirocupak Miro Cupak VP Engineering, DNAstack 01/06/2018 Writing clean code with Java 9+
  • 2. @mirocupak Clarity, simplicity, brevity, humanity !2 http://www.osnews.com/story/19266/WTFs_m https://xkcd.com/1695/ https://theamericanscholar.org/writing-english-as-a-second-language/
  • 4. @mirocupak Features !4 • Factory methods for collections. • Improved try-with-resources. • Private methods in interfaces. • Stream API enhancements. • Extensions to Optional. • HTTP/2 client. • Type inference.
  • 6. @mirocupak Factory methods for collections !6 • Obtain immutable collections via of/ofEntries methods. • Create immutable copies of collections via copyOf (Java 10). • Static import java.util.Map.entry. • Less verbose, no static initializer blocks. • Don’t use Arrays.asList or Stream.of as shortcuts for creating collections. • Don’t use external libraries if you only need immutable collections (Guava). • No need to worry about leaving references to underlying collections. • Thread-safe and can be shared freely (no need for defensive copies). • Good performance. • Don’t create mutable collections unless necessary.
  • 8. @mirocupak Improved try-with-resources !8 • Always prefer try-with-resources, don’t use try-finally and definitely don’t use finalizers to close resources. • Be aware of convenience methods, such as InputStream.transferTo. • Don’t create unnecessary helper objects.
  • 10. @mirocupak Private methods in interfaces !10 • Default methods, like all other methods, should be short. • DRY. • Use private methods to keep default methods short. • Use private methods to extract shared core of default methods. • Use default methods for providing standard implementations for new interface code. • Don’t use default methods to extend existing interfaces unless necessary.
  • 12. @mirocupak Stream API enhancements !12 • Be aware of new stream methods: takeWhile, dropWhile, iterate. • Prefer collecting into immutable collections using toUnmodifiableList, toUnmodifiableSet, toUnmodifiableMap. • Check for convenience stream methods before converting to streams manually (e.g. Matcher, LocalDate). • Avoid unnecessary null checks with ofNullable. • Streams are suitable for more use cases now, but not all use cases. • Don’t overuse streams as they can make code hard to read and difficult to maintain.
  • 14. @mirocupak Extensions to Optional !14 • Use ifPresentOrElse instead of if-isPresent construct. • or provides a clean fluent way of chaining behaviour on Optionals. • Be aware of orElse* methods, e.g. the new orElseThrow (Java 10). • Use stream to take advantage of the lazy nature of streams and handle streams of Optionals. • Remember that isPresent is rarely the answer.
  • 16. @mirocupak HTTP/2 client !16 • Clean separation: HttpClient, HttpRequest, HttpResponse. • HttpURLConnection is not pleasant to use. • Avoid APIs with side effects. • The new client API is versatile, flexible and clean. • Prefer functionality in the JDK to external libraries. • But aware it’s an incubator module.
  • 18. @mirocupak Diamond operator with anonymous classes !18 • Use <> for anonymous classes, like everywhere else. • <> improves readability and consistency. • Use anonymous classes only when needed (e.g. abstract classes, interfaces with multiple abstract methods…), otherwise replace with lambdas.
  • 19. @mirocupak Local variable type inference !19 • Does not replace static typing. • Generally good. • Reduces boilerplate and improves readability. • Helps with maintenance and refactoring. • Use for local variables with initializers (especially constructors) and for loops. • Can’t use for method formals, constructor formals, method return types, fields, catch formals, null or array initializers, lambdas, method references, or any other kind of variable declaration. • Consider whether to use when the generated type is not obvious. • But use for complex types when breaking chained or nested expressions with local variables. • Primitive types might surprise you, be careful (e.g. byte, short, long all inferred as int).
  • 20. @mirocupak Local variable type inference !20 • Be very careful about combining with <> and generic methods (e.g. var list = new ArrayList<>()). • Probably not the best idea to use with anonymous classes. • Use carefully chosen and expressive variable names. • Don’t use Hungarian notation. • Don’t rely on IDEs. • Minimize the scope of local variables. • Declare variable when it’s first used. • Declaration not containing an initializer (i.e. you can’t use var) often indicates the scope is not minimal. • Prefer for loops to while loops. • Keep methods small and focused. • Code to the interface pattern does not work, but that’s kind of OK.
  • 21. @mirocupak Questions? !21 More info: Session notes on Twitter. Blog: https://mirocupak.com/