SlideShare a Scribd company logo
1 of 20
Download to read offline
@mirocupakDJUG
The good, the bad, and the ugly
of Java API design
Miro Cupak
Co-founder & VP Engineering, DNAstack
October 02, 2019
@mirocupakDJUG 2
Features
• Collections API.
• Stack-walking API.
• Process API.
• HTTP client API.
@mirocupakDJUG
Collections API
3
@mirocupakDJUG 4
Best practices
• Take advantage of convenience factory methods for collections.
• Immutable collections via of/ofEntries and copies via copyOf.
• Less verbose, no static initializer blocks.
• Create immutable collections by default, only add mutability when needed.
• No need to worry about forgetting references to underlying collections.
• Thread-safe and can be shared freely (no need for defensive copies).
• Good performance.
• Prefer collecting into immutable collections using toUnmodifiableList,
toUnmodifiableSet, toUnmodifiableMap.
• Use toArray to convert collections to arrays.
@mirocupakDJUG 5
Antipatterns
• Obtaining collections through other data structures (Arrays.asList,
Stream.of).
• Pulling in external dependencies only to obtain immutable collections (e.g.
Guava and its Immutable*).
• Instance-initializer construct in an anonymous inner class to instantiate
collections.
• Performance over clean APIs ([List, Set, Map].of).
@mirocupakDJUG 6
Patterns
• Static factory methods to create objects (of/ofEntries/copyOf).
• Name concisely (convention: of).
• Concrete classes not as part of the public API with static methods on
interfaces returning instances (pattern for implementation flexibility).
• Static import when readability not jeopardized (java.util.Map.entry).
• Tuple wrapper objects and convenience methods to generate them when
multiple varargs needed (Map.ofEntries).
• Converting between types via copyOf.
• Constructor reference as a generating function (array in a toArray call).
• Immutability by default (collections with copies and collectors).
@mirocupakDJUG
Stack-walking API
7
@mirocupakDJUG 8
Best practices
• Take advantage of the Stream API to access only certain elements.
• Be aware of StackWalker.Option.
• Don’t resolve classes manually.
• Use to show hidden and reflection frames.
@mirocupakDJUG 9
Antipatterns
• Using [Thread, Throwable].getStackTrace() to traverse selected
frames of the execution stack.
• Treating execution stack as text.
• Using strings to represent Class instances.
• Accessing things eagerly when only parts of them are needed.
• Surprising hidden method behaviour (omitting elements of the stack for
performance).
@mirocupakDJUG 10
Patterns
• Collections over arrays.
• Leveraging Stream API in API design.
• Choose suitable represetations (don’t model everything as strings).
• Good performance through lazy access via streams.
• Methods accepting functions on streams as parameters to maintain
consistent state and control (walk()).
• Obtaining configured instances via static factory methods parameterized
with enums (getInstance()).
• Work with a security manager (secure access to Class objects).
• Permission checks when constructing instead of using an object.
@mirocupakDJUG
Process API
11
@mirocupakDJUG 12
Best practices
• ProcessHandle is a clean way of obtaining information about processes.
• Take advantage of convenience methods: pid, info, command…
• Trigger actions on process termination via onExit.
• Connect ProcessBuilder with ProcessHandle via toHandle.
@mirocupakDJUG 13
Antipatterns
• Accessing process information via MXBeans or OS utilities.
• Pulling in external libraries for simple process management (e.g. Apache
Commons Exec).
• Incomplete APIs - providing functionality to start hard-to-manage resources
without providing the functionality to obtain information about them.
• APIs leading the clients to use non-portable constructs.
@mirocupakDJUG 14
Patterns
• Providing convenience methods for commonly used functionality.
• Compact fluent API to access nested information.
• Nested public interfaces to group and organize (ProcessHandle.Info).
• Using convenient static factory methods to obtain instances
(ProcessHandle.[current, of, allProcesses]).
• Returning streams instead of collections to streamline lazy processing of
many elements (allProcesses, children, descendants…).
• Returning CompletableFuture instances in asynchronous APIs
(onExit).
• Providing adapters via to* methods (toHandle).
@mirocupakDJUG
HTTP client API
15
@mirocupakDJUG 16
Best practices
• Clear organization: HttpClient, HttpRequest, HttpResponse.
• HttpURLConnection is not pleasant to use.
• The new client API is versatile, flexible and clean.
• Prefer functionality in the JDK to external libraries.
@mirocupakDJUG 17
Antipatterns
• Using HttpURLConnection directly.
• Inconsistent capitalization (HttpURLConnection).
• Overly abstract and general APIs (URLConnection).
• Unclear conceptual API model (URL).
• Type casting needed to obtain the right instance (openConnection).
• Using strings where methods or enums would be more practical
(setRequestMethod(“GET”)).
• Requiring the client to use I/O boilerplate (BufferedReader/
InputStreamReader/InputStream…).
@mirocupakDJUG 18
Antipatterns
• Mandatory blocking network I/O.
• Side effects and hidden assumptions (getInputStream).
• Inconsistent behaviour across APIs (URLConnection vs. Socket).
@mirocupakDJUG 19
Patterns
• Clear separation of concepts at the class level (HttpClient,
HttpRequest, HttpResponse).
• Builder.
• Asynchronous via CompletableFuture.
• Clear and consistent naming.
• Convenience methods to access commonly used features (statusCode,
body).
@mirocupakDJUG
Questions?
20

More Related Content

What's hot

State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015
State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015
State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015Dropsolid
 
Breathing new life into Apache Oozie with Apache Ambari Workflow Manager
Breathing new life into Apache Oozie with Apache Ambari Workflow ManagerBreathing new life into Apache Oozie with Apache Ambari Workflow Manager
Breathing new life into Apache Oozie with Apache Ambari Workflow ManagerArtem Ervits
 
Creating Modular Test-Driven SPAs with Spring and AngularJS
Creating Modular Test-Driven SPAs with Spring and AngularJSCreating Modular Test-Driven SPAs with Spring and AngularJS
Creating Modular Test-Driven SPAs with Spring and AngularJSGunnar Hillert
 
Training Slides: 303 - Replicating out of a Cluster
Training Slides: 303 - Replicating out of a ClusterTraining Slides: 303 - Replicating out of a Cluster
Training Slides: 303 - Replicating out of a ClusterContinuent
 
Spring batch introduction
Spring batch introductionSpring batch introduction
Spring batch introductionAlex Fernandez
 

What's hot (9)

Parallel Programming
Parallel ProgrammingParallel Programming
Parallel Programming
 
State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015
State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015
State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015
 
Breathing new life into Apache Oozie with Apache Ambari Workflow Manager
Breathing new life into Apache Oozie with Apache Ambari Workflow ManagerBreathing new life into Apache Oozie with Apache Ambari Workflow Manager
Breathing new life into Apache Oozie with Apache Ambari Workflow Manager
 
Gradle - Build System
Gradle - Build SystemGradle - Build System
Gradle - Build System
 
Creating Modular Test-Driven SPAs with Spring and AngularJS
Creating Modular Test-Driven SPAs with Spring and AngularJSCreating Modular Test-Driven SPAs with Spring and AngularJS
Creating Modular Test-Driven SPAs with Spring and AngularJS
 
Reactive Streams
Reactive StreamsReactive Streams
Reactive Streams
 
Training Slides: 303 - Replicating out of a Cluster
Training Slides: 303 - Replicating out of a ClusterTraining Slides: 303 - Replicating out of a Cluster
Training Slides: 303 - Replicating out of a Cluster
 
The Spring Update
The Spring UpdateThe Spring Update
The Spring Update
 
Spring batch introduction
Spring batch introductionSpring batch introduction
Spring batch introduction
 

Similar to The good, the bad, and the ugly of Java API design

Hadoop Eagle - Real Time Monitoring Framework for eBay Hadoop
Hadoop Eagle - Real Time Monitoring Framework for eBay HadoopHadoop Eagle - Real Time Monitoring Framework for eBay Hadoop
Hadoop Eagle - Real Time Monitoring Framework for eBay HadoopDataWorks Summit
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at TwitterAlex Payne
 
Apache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM AlternativeApache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM AlternativeAndrus Adamchik
 
Ratpack Web Framework
Ratpack Web FrameworkRatpack Web Framework
Ratpack Web FrameworkDaniel Woods
 
Eclipse Apricot
Eclipse ApricotEclipse Apricot
Eclipse ApricotNuxeo
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO DevsWO Community
 
Java EE revisits design patterns
Java EE revisits design patternsJava EE revisits design patterns
Java EE revisits design patternsAlex Theedom
 
Introducing Apricot, The Eclipse Content Management Platform
Introducing Apricot, The Eclipse Content Management PlatformIntroducing Apricot, The Eclipse Content Management Platform
Introducing Apricot, The Eclipse Content Management PlatformNuxeo
 
Master class in modern Java
Master class in modern JavaMaster class in modern Java
Master class in modern JavaMiro Cupak
 
Master class in modern Java
Master class in modern JavaMaster class in modern Java
Master class in modern JavaMiro Cupak
 
Efficient HTTP applications on the JVM with Ratpack - Voxxed Days Berlin 2016
Efficient HTTP applications on the JVM with Ratpack - Voxxed Days Berlin 2016Efficient HTTP applications on the JVM with Ratpack - Voxxed Days Berlin 2016
Efficient HTTP applications on the JVM with Ratpack - Voxxed Days Berlin 2016Alvaro Sanchez-Mariscal
 
ASP.NET MVC Best Practices malisa ncube
ASP.NET MVC Best Practices   malisa ncubeASP.NET MVC Best Practices   malisa ncube
ASP.NET MVC Best Practices malisa ncubeMalisa Ncube
 
Java EE Revisits Design Patterns
Java EE Revisits Design PatternsJava EE Revisits Design Patterns
Java EE Revisits Design PatternsAlex Theedom
 
Intro to Apache Apex @ Women in Big Data
Intro to Apache Apex @ Women in Big DataIntro to Apache Apex @ Women in Big Data
Intro to Apache Apex @ Women in Big DataApache Apex
 
Lessons learned from embedding Cassandra in xPatterns
Lessons learned from embedding Cassandra in xPatternsLessons learned from embedding Cassandra in xPatterns
Lessons learned from embedding Cassandra in xPatternsClaudiu Barbura
 
Backbonification for dummies - Arrrrug 10/1/2012
Backbonification for dummies - Arrrrug 10/1/2012Backbonification for dummies - Arrrrug 10/1/2012
Backbonification for dummies - Arrrrug 10/1/2012Dimitri de Putte
 
SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016Alex Theedom
 

Similar to The good, the bad, and the ugly of Java API design (20)

Show Some Spine!
Show Some Spine!Show Some Spine!
Show Some Spine!
 
Hadoop Eagle - Real Time Monitoring Framework for eBay Hadoop
Hadoop Eagle - Real Time Monitoring Framework for eBay HadoopHadoop Eagle - Real Time Monitoring Framework for eBay Hadoop
Hadoop Eagle - Real Time Monitoring Framework for eBay Hadoop
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
Apache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM AlternativeApache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM Alternative
 
Ratpack Web Framework
Ratpack Web FrameworkRatpack Web Framework
Ratpack Web Framework
 
Eclipse Apricot
Eclipse ApricotEclipse Apricot
Eclipse Apricot
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO Devs
 
Java EE revisits design patterns
Java EE revisits design patternsJava EE revisits design patterns
Java EE revisits design patterns
 
AngularJS
AngularJSAngularJS
AngularJS
 
Introducing Apricot, The Eclipse Content Management Platform
Introducing Apricot, The Eclipse Content Management PlatformIntroducing Apricot, The Eclipse Content Management Platform
Introducing Apricot, The Eclipse Content Management Platform
 
Master class in modern Java
Master class in modern JavaMaster class in modern Java
Master class in modern Java
 
Master class in modern Java
Master class in modern JavaMaster class in modern Java
Master class in modern Java
 
Efficient HTTP applications on the JVM with Ratpack - Voxxed Days Berlin 2016
Efficient HTTP applications on the JVM with Ratpack - Voxxed Days Berlin 2016Efficient HTTP applications on the JVM with Ratpack - Voxxed Days Berlin 2016
Efficient HTTP applications on the JVM with Ratpack - Voxxed Days Berlin 2016
 
ASP.NET MVC Best Practices malisa ncube
ASP.NET MVC Best Practices   malisa ncubeASP.NET MVC Best Practices   malisa ncube
ASP.NET MVC Best Practices malisa ncube
 
Java EE Revisits Design Patterns
Java EE Revisits Design PatternsJava EE Revisits Design Patterns
Java EE Revisits Design Patterns
 
JCache Using JCache
JCache Using JCacheJCache Using JCache
JCache Using JCache
 
Intro to Apache Apex @ Women in Big Data
Intro to Apache Apex @ Women in Big DataIntro to Apache Apex @ Women in Big Data
Intro to Apache Apex @ Women in Big Data
 
Lessons learned from embedding Cassandra in xPatterns
Lessons learned from embedding Cassandra in xPatternsLessons learned from embedding Cassandra in xPatterns
Lessons learned from embedding Cassandra in xPatterns
 
Backbonification for dummies - Arrrrug 10/1/2012
Backbonification for dummies - Arrrrug 10/1/2012Backbonification for dummies - Arrrrug 10/1/2012
Backbonification for dummies - Arrrrug 10/1/2012
 
SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016SE2016 - Java EE revisits design patterns 2016
SE2016 - Java EE revisits design patterns 2016
 

More from Miro Cupak

Exploring the latest and greatest from Java 14
Exploring the latest and greatest from Java 14Exploring the latest and greatest from Java 14
Exploring the latest and greatest from Java 14Miro Cupak
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in JavaMiro Cupak
 
Exploring the last year of Java
Exploring the last year of JavaExploring the last year of Java
Exploring the last year of JavaMiro Cupak
 
Local variable type inference - Will it compile?
Local variable type inference - Will it compile?Local variable type inference - Will it compile?
Local variable type inference - Will it compile?Miro Cupak
 
Local variable type inference - Will it compile?
Local variable type inference - Will it compile?Local variable type inference - Will it compile?
Local variable type inference - Will it compile?Miro Cupak
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in JavaMiro Cupak
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in JavaMiro Cupak
 
Writing clean code with modern Java
Writing clean code with modern JavaWriting clean code with modern Java
Writing clean code with modern JavaMiro Cupak
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in JavaMiro Cupak
 
Writing clean code with modern Java
Writing clean code with modern JavaWriting clean code with modern Java
Writing clean code with modern JavaMiro Cupak
 
Exploring what's new in Java 10 and 11 (and 12)
Exploring what's new in Java 10 and 11 (and 12)Exploring what's new in Java 10 and 11 (and 12)
Exploring what's new in Java 10 and 11 (and 12)Miro Cupak
 
Exploring what's new in Java 10 and 11
Exploring what's new in Java 10 and 11Exploring what's new in Java 10 and 11
Exploring what's new in Java 10 and 11Miro Cupak
 
Exploring what's new in Java in 2018
Exploring what's new in Java in 2018Exploring what's new in Java in 2018
Exploring what's new in Java in 2018Miro Cupak
 
Reactive programming in Java
Reactive programming in JavaReactive programming in Java
Reactive programming in JavaMiro Cupak
 
Master class in Java in 2018
Master class in Java in 2018Master class in Java in 2018
Master class in Java in 2018Miro Cupak
 
Exploring reactive programming with Java
Exploring reactive programming with JavaExploring reactive programming with Java
Exploring reactive programming with JavaMiro Cupak
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in JavaMiro Cupak
 
Writing clean code with Java in 2018
Writing clean code with Java in 2018Writing clean code with Java in 2018
Writing clean code with Java in 2018Miro Cupak
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in JavaMiro Cupak
 
Pushing boundaries of types with modern Java
Pushing boundaries of types with modern JavaPushing boundaries of types with modern Java
Pushing boundaries of types with modern JavaMiro Cupak
 

More from Miro Cupak (20)

Exploring the latest and greatest from Java 14
Exploring the latest and greatest from Java 14Exploring the latest and greatest from Java 14
Exploring the latest and greatest from Java 14
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in Java
 
Exploring the last year of Java
Exploring the last year of JavaExploring the last year of Java
Exploring the last year of Java
 
Local variable type inference - Will it compile?
Local variable type inference - Will it compile?Local variable type inference - Will it compile?
Local variable type inference - Will it compile?
 
Local variable type inference - Will it compile?
Local variable type inference - Will it compile?Local variable type inference - Will it compile?
Local variable type inference - Will it compile?
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in Java
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in Java
 
Writing clean code with modern Java
Writing clean code with modern JavaWriting clean code with modern Java
Writing clean code with modern Java
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in Java
 
Writing clean code with modern Java
Writing clean code with modern JavaWriting clean code with modern Java
Writing clean code with modern Java
 
Exploring what's new in Java 10 and 11 (and 12)
Exploring what's new in Java 10 and 11 (and 12)Exploring what's new in Java 10 and 11 (and 12)
Exploring what's new in Java 10 and 11 (and 12)
 
Exploring what's new in Java 10 and 11
Exploring what's new in Java 10 and 11Exploring what's new in Java 10 and 11
Exploring what's new in Java 10 and 11
 
Exploring what's new in Java in 2018
Exploring what's new in Java in 2018Exploring what's new in Java in 2018
Exploring what's new in Java in 2018
 
Reactive programming in Java
Reactive programming in JavaReactive programming in Java
Reactive programming in Java
 
Master class in Java in 2018
Master class in Java in 2018Master class in Java in 2018
Master class in Java in 2018
 
Exploring reactive programming with Java
Exploring reactive programming with JavaExploring reactive programming with Java
Exploring reactive programming with Java
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in Java
 
Writing clean code with Java in 2018
Writing clean code with Java in 2018Writing clean code with Java in 2018
Writing clean code with Java in 2018
 
Exploring reactive programming in Java
Exploring reactive programming in JavaExploring reactive programming in Java
Exploring reactive programming in Java
 
Pushing boundaries of types with modern Java
Pushing boundaries of types with modern JavaPushing boundaries of types with modern Java
Pushing boundaries of types with modern Java
 

Recently uploaded

Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
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
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
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
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
(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
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
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.
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 

Recently uploaded (20)

Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
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...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
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
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
(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...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
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...
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 

The good, the bad, and the ugly of Java API design

  • 1. @mirocupakDJUG The good, the bad, and the ugly of Java API design Miro Cupak Co-founder & VP Engineering, DNAstack October 02, 2019
  • 2. @mirocupakDJUG 2 Features • Collections API. • Stack-walking API. • Process API. • HTTP client API.
  • 4. @mirocupakDJUG 4 Best practices • Take advantage of convenience factory methods for collections. • Immutable collections via of/ofEntries and copies via copyOf. • Less verbose, no static initializer blocks. • Create immutable collections by default, only add mutability when needed. • No need to worry about forgetting references to underlying collections. • Thread-safe and can be shared freely (no need for defensive copies). • Good performance. • Prefer collecting into immutable collections using toUnmodifiableList, toUnmodifiableSet, toUnmodifiableMap. • Use toArray to convert collections to arrays.
  • 5. @mirocupakDJUG 5 Antipatterns • Obtaining collections through other data structures (Arrays.asList, Stream.of). • Pulling in external dependencies only to obtain immutable collections (e.g. Guava and its Immutable*). • Instance-initializer construct in an anonymous inner class to instantiate collections. • Performance over clean APIs ([List, Set, Map].of).
  • 6. @mirocupakDJUG 6 Patterns • Static factory methods to create objects (of/ofEntries/copyOf). • Name concisely (convention: of). • Concrete classes not as part of the public API with static methods on interfaces returning instances (pattern for implementation flexibility). • Static import when readability not jeopardized (java.util.Map.entry). • Tuple wrapper objects and convenience methods to generate them when multiple varargs needed (Map.ofEntries). • Converting between types via copyOf. • Constructor reference as a generating function (array in a toArray call). • Immutability by default (collections with copies and collectors).
  • 8. @mirocupakDJUG 8 Best practices • Take advantage of the Stream API to access only certain elements. • Be aware of StackWalker.Option. • Don’t resolve classes manually. • Use to show hidden and reflection frames.
  • 9. @mirocupakDJUG 9 Antipatterns • Using [Thread, Throwable].getStackTrace() to traverse selected frames of the execution stack. • Treating execution stack as text. • Using strings to represent Class instances. • Accessing things eagerly when only parts of them are needed. • Surprising hidden method behaviour (omitting elements of the stack for performance).
  • 10. @mirocupakDJUG 10 Patterns • Collections over arrays. • Leveraging Stream API in API design. • Choose suitable represetations (don’t model everything as strings). • Good performance through lazy access via streams. • Methods accepting functions on streams as parameters to maintain consistent state and control (walk()). • Obtaining configured instances via static factory methods parameterized with enums (getInstance()). • Work with a security manager (secure access to Class objects). • Permission checks when constructing instead of using an object.
  • 12. @mirocupakDJUG 12 Best practices • ProcessHandle is a clean way of obtaining information about processes. • Take advantage of convenience methods: pid, info, command… • Trigger actions on process termination via onExit. • Connect ProcessBuilder with ProcessHandle via toHandle.
  • 13. @mirocupakDJUG 13 Antipatterns • Accessing process information via MXBeans or OS utilities. • Pulling in external libraries for simple process management (e.g. Apache Commons Exec). • Incomplete APIs - providing functionality to start hard-to-manage resources without providing the functionality to obtain information about them. • APIs leading the clients to use non-portable constructs.
  • 14. @mirocupakDJUG 14 Patterns • Providing convenience methods for commonly used functionality. • Compact fluent API to access nested information. • Nested public interfaces to group and organize (ProcessHandle.Info). • Using convenient static factory methods to obtain instances (ProcessHandle.[current, of, allProcesses]). • Returning streams instead of collections to streamline lazy processing of many elements (allProcesses, children, descendants…). • Returning CompletableFuture instances in asynchronous APIs (onExit). • Providing adapters via to* methods (toHandle).
  • 16. @mirocupakDJUG 16 Best practices • Clear organization: HttpClient, HttpRequest, HttpResponse. • HttpURLConnection is not pleasant to use. • The new client API is versatile, flexible and clean. • Prefer functionality in the JDK to external libraries.
  • 17. @mirocupakDJUG 17 Antipatterns • Using HttpURLConnection directly. • Inconsistent capitalization (HttpURLConnection). • Overly abstract and general APIs (URLConnection). • Unclear conceptual API model (URL). • Type casting needed to obtain the right instance (openConnection). • Using strings where methods or enums would be more practical (setRequestMethod(“GET”)). • Requiring the client to use I/O boilerplate (BufferedReader/ InputStreamReader/InputStream…).
  • 18. @mirocupakDJUG 18 Antipatterns • Mandatory blocking network I/O. • Side effects and hidden assumptions (getInputStream). • Inconsistent behaviour across APIs (URLConnection vs. Socket).
  • 19. @mirocupakDJUG 19 Patterns • Clear separation of concepts at the class level (HttpClient, HttpRequest, HttpResponse). • Builder. • Asynchronous via CompletableFuture. • Clear and consistent naming. • Convenience methods to access commonly used features (statusCode, body).