SlideShare une entreprise Scribd logo
1  sur  28
Practices and Tools for
Building Better APIs
Peter Hendriks - IT Architect, Info Support BV
CON4374
About Peter
• Working at Info Support…
• In a country, far, far away…
• Netherlands, Europe
• Coding on challenging
Java applications
Objectives of this talk
• Focus on Java application developer perspective
• What is an API and why should you care about it
• How you can identify and build better APIs
• Measuring API in an existing codebase
What is an API
• Code that is directly used to connect two software modules
• “API Consumer”: module that calls the API
• “API Implementer”: module that provides behavior for API
public class CollectionsDemo {
public static void main(String args[]) {
// create an array of string objs
String init[] = { "One", "Two", "Three" };
// create one list
List list = new ArrayList(Arrays.asList(init));
System.out.println("List value before: "+list);
// sort the list
Collections.sort(list);
System.out.println("List value after: "+list);
}
}
// Load expected data from an XML dataset
IDataSet expectedDataSet = new FlatXmlDataSetBuilder()
.build(new File("expectedDataSet.xml"));
<dataset>
<PERSON NAME="Bob" LAST_NAME="Doe" AGE="18"/>
<PERSON NAME="Alice" LAST_NAME="Foo" AGE="23"/>
<PERSON NAME="Charlie" LAST_NAME="Brown" AGE="42"/>
</dataset>
API is key to a successful module design
Essential for building large-scale software:
• Reuse
• Independent change
• Separation of concerns
Modular design key to support agile practices at scale
Shared code
Customer
Front-End
Warehouse
Front-End
Order
Management
You are using a lot of APIs
• Modern software development
relies on reuse of modules
• OS, Java Platform, Libraries, Application
Server, etc.
• System to System APIs increasingly
important
• Many public APIs like Twitter, Google,
Facebook, SalesForce, etc.
• SOA
Java SE
Java EE
Log4j Spring
Module
Module Module
OS
Twitter
Auth
Database
SOA
Distance to API implementation
increasing
• API quality matters more when implementation becomes a black box
You
Same team Different team Open source Binary only Other datacenter
API
Impl
The API we use shapes our code
• Most code we write calls an API
• Code that calls an API is shaped to fit the API
• Therefore, APIs determine the shape of application code
• In some ways, even more impactful than high level design, test driven
development or code craftsmanship
http://docs.oracle.com/javaee/1.4/tutorial/examples/jaxp/xslt/samples/TransformationApp04.java
public class TransformationApp04 {
public static void main(String[] argv) {
if (argv.length != 1) {
System.err.println("Usage: java TransformationApp filename");
System.exit(1);
}
// Create the sax "parser".
AddressBookReader02 saxReader = new AddressBookReader02();
try {
File f = new File(argv[0]);
// Use a Transformer for output
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
// Use the parser as a SAX source for input
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
InputSource inputSource = new InputSource(fr);
SAXSource source = new SAXSource(saxReader, inputSource);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
} catch (TransformerConfigurationException tce) {
// Error generated by the parser
System.out.println("n** Transformer Factory error");
System.out.println(" " + tce.getMessage());
Doing stuff
with XML…
var json_data = JSON.stringify(obj);
Trademarks of a better API
Trademarks of a better API
1. Valuable (always important)
• Value = benefits - costs
2. Usable (more important if used more)
• Easy to learn, productive, error-proof
3. Stable (more important if used more and longer)
• Able to enhance and grow features without breaking existing consumer code
API Design == Human Interface design
• Although API is for machine/machine interaction, APIs are interpreted
by programmers to write the code
• Programmers are humans!
API is not just about capability and structural design, but also
about human understanding
API Usability quantified
Generic usability model by Ben Shneiderman:
• Learnability: How easy is it to accomplish basic tasks the first time?
• Efficiency: Once users learned the design, how quickly can they
perform tasks?
• Memorability: When users return after a while, how easily can they
re-establish proficiency?
• Errors: How many errors do users make, how severe are these errors,
and how easily can they recover from the errors?
• Satisfaction: How pleasant is it to use the design?
Building Better APIs
Designing an API: multiple perspectives
public class Document {
private List<Page> pages = new ArrayList<>();
public Page addPage() {
Page page = new Page();
pages.add(page);
page.setPageNumber(pages.size());
return page;
}
public void report() {...}
}
document.addPage().setContents("Once upon a time...");
UML: Names, Completeness, Grouping
Implementation: can it be built
API usage: how usable is it
Initial design: examples first
• Examples most important in API documentation
• Concrete use case, usability check
• Make examples exemplary
• Example code will be copy-pasted
• Create a cheat sheet
• Improves learnability
• Shows design issues
Full Java EE cheat sheet on: http://www.physics.usyd.edu.au/~rennie/javaEEReferenceSheet.pdf
When in doubt leave it out
• Smaller APIs are easier to use and maintain
• Less classes
• Less methods
• Less parameters/return values
• Easier to add API later vs removing or changing it
• Having a small API increases stability
Limit API consumer code to a minimum
• Some API constructs lead to verbose consumer code
• Extending class/implementing interface
• Checked Exception
• Required casting
• Required Generic Type
• Hard coded parameter value
• Required if, for, while, try
• Required synchronization/locking
Example: limiting logging code
// classic debug call (log4j 1.x)
// check debug to prevent string creation
if(logger.isDebugEnabled()) {
logger.debug("The new entry is " + entry + ".");
}
// parameterized logging (slf4j)
logger.debug("The new entry is {}.", entry);
public void debug(Object message) {
if (isDebugEnabled()) {
// .. implementation
}
}
public void debug(String format, Object arg) {
if (isDebugEnabled()) {
// .. implementation
}
}
Using Log4J API Using SLF4J API
SLF4J ImplementationLog4J Implementation
Better
Java 8 Lambda expressions
List<Integer> numbers = Arrays.asList(1, 2);
for (int number : numbers) {
if (numbers % 2 == 0) {
System.out.println(number);
}
}
forEachEven(numbers, value ->
System.out.println(value));
forEachEven(numbers, new Consumer<Integer>() {
public void accept(Integer value) {
System.out.println(value);
}
});
Without Lambda expressions With Lambda
Better
Be predictable and obvious
• Methods should be able to be called in any order
• Constructor should only construct
• Don’t have surprising side effects
public class TopicListener {
public TopicListener(Topic topic) {
if (!topic.register(this))
throw new SystemException("error!");
}
}
public class TopicListener {
private final Topic topic;
public TopicListener(Topic topic) {
this.topic = topic;
}
public void start() {
if (!topic.register(this))
throw new SystemException("error!");
}
}
Better
Predictable state
• Limit the use of null as input or output
• Fail fast, fail hard on wrong input
public void save(String filename) {
Objects.requireNonNull(filename);
... // save happens here
}
public void save(String filename) {
if (filename == null) {
return; // bad api: error is ignored!
}
... // save happens here
}
Better
FindBugs and JSR 305
• JSR 305: Annotations for Software Defect Detection (Dormant)
• @Nonnull: may never be null
• @CheckForNull: should always be checked before dereferenced
• @Nullable: caller decides if null check is needed
• Alternatives: Checker framework, Eclipse, IntelliJ IDEA
FindBugs demo in Eclipse
Investigating existing codebases
• People
• Team knowledge
• Policy, “best practices”, conventions
• Elaborate explanation necessary, “hard to do”
• Bug list/exceptions/stack traces
• Tools:
• Finding most used API: Dependency Structure Matrix (DSM)
Dependency Structure Matrix
Document Page TextBlock
Document -
Page 2 -
TextBlock 10 -
Classes/Packages
# of direct dependencies from
Document to Page
Demo: SonarQube DSM matrix
API design cheat sheet (Q & A)
A Better API is:
1. Valuable
2. Usable
3. Stable
API usability:
• Learnability
• Efficiency
• Memorability
• Error rate
• Satisfaction
API Design Perspectives:
UML: names, completeness, grouping
Implementation: can it be built
API usage: how usable is it
Examples First
API Design practices:
When in doubt leave it out
Limit API consumer code to a minimum
• Extending class/implementing interface
• Checked Exception
• Required casting
• Required Generic Type
• Hard coded parameter value
• Required if, for, while, try
• Required synchronization/locking
Be predictable and obvious
• Methods should be calleable in any order
• Constructor should only construct
• Don’t have surprising side effects
• Limit the use of null as input or output
• Fail fast, fail hard on wrong input
Document Page TextBlock
Document -
Page 2 -
TextBlock 10 -
DSM: finding most used API
JSR 305/FindBugs:
@Nonnull: may never be null
@CheckForNull: always check
@Nullable: caller decides null check
When API matters:
• Modular design
• Reuse 3rd party
• Distance to impl.

Contenu connexe

Tendances

Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
seleniumconf
 
Cross-platform mobile apps with Apache Cordova
Cross-platform mobile apps with Apache CordovaCross-platform mobile apps with Apache Cordova
Cross-platform mobile apps with Apache Cordova
Ivano Malavolta
 
Tech io spa_angularjs_20130814_v0.9.5
Tech io spa_angularjs_20130814_v0.9.5Tech io spa_angularjs_20130814_v0.9.5
Tech io spa_angularjs_20130814_v0.9.5
Ganesh Kondal
 

Tendances (18)

Programming Paradigm & Languages
Programming Paradigm & LanguagesProgramming Paradigm & Languages
Programming Paradigm & Languages
 
Diving into Java Class Loader
Diving into Java Class LoaderDiving into Java Class Loader
Diving into Java Class Loader
 
Advanced iOS Debbuging (Reloaded)
Advanced iOS Debbuging (Reloaded)Advanced iOS Debbuging (Reloaded)
Advanced iOS Debbuging (Reloaded)
 
Basic Selenium Training
Basic Selenium TrainingBasic Selenium Training
Basic Selenium Training
 
MVC by asp.net development company in india
MVC by asp.net development company in indiaMVC by asp.net development company in india
MVC by asp.net development company in india
 
API Virtualization: Mocking on Steroids
API Virtualization: Mocking on SteroidsAPI Virtualization: Mocking on Steroids
API Virtualization: Mocking on Steroids
 
Software Automation Testing Introduction
Software Automation Testing IntroductionSoftware Automation Testing Introduction
Software Automation Testing Introduction
 
Getting Started with Zend Framework
Getting Started with Zend FrameworkGetting Started with Zend Framework
Getting Started with Zend Framework
 
C# fundamentals Part 2
C# fundamentals Part 2C# fundamentals Part 2
C# fundamentals Part 2
 
Eclipse
EclipseEclipse
Eclipse
 
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
 
Power-Up Your Test Suite with OLE Automation by Joshua Russell
Power-Up Your Test Suite with OLE Automation by Joshua RussellPower-Up Your Test Suite with OLE Automation by Joshua Russell
Power-Up Your Test Suite with OLE Automation by Joshua Russell
 
Another API-Blueprint, RAML and Swagger Comparison
Another API-Blueprint, RAML and Swagger ComparisonAnother API-Blueprint, RAML and Swagger Comparison
Another API-Blueprint, RAML and Swagger Comparison
 
T4 presentation
T4 presentationT4 presentation
T4 presentation
 
Api tools overview
Api tools overviewApi tools overview
Api tools overview
 
Cross-platform mobile apps with Apache Cordova
Cross-platform mobile apps with Apache CordovaCross-platform mobile apps with Apache Cordova
Cross-platform mobile apps with Apache Cordova
 
Tech io spa_angularjs_20130814_v0.9.5
Tech io spa_angularjs_20130814_v0.9.5Tech io spa_angularjs_20130814_v0.9.5
Tech io spa_angularjs_20130814_v0.9.5
 
Cordova: APIs and instruments
Cordova: APIs and instrumentsCordova: APIs and instruments
Cordova: APIs and instruments
 

En vedette

Feliz cumple ama!!
Feliz cumple ama!!Feliz cumple ama!!
Feliz cumple ama!!
fionafer
 
ชุมนุมสหกรณ์ 22 ม ค 56
ชุมนุมสหกรณ์ 22 ม ค 56ชุมนุมสหกรณ์ 22 ม ค 56
ชุมนุมสหกรณ์ 22 ม ค 56
nachol_fsct
 

En vedette (10)

200911051727210.prueba lenguaje
200911051727210.prueba lenguaje200911051727210.prueba lenguaje
200911051727210.prueba lenguaje
 
The tension between agile and architecture
The tension between agile and architectureThe tension between agile and architecture
The tension between agile and architecture
 
paging
pagingpaging
paging
 
Feliz cumple ama!!
Feliz cumple ama!!Feliz cumple ama!!
Feliz cumple ama!!
 
Mobile mindset study
Mobile mindset studyMobile mindset study
Mobile mindset study
 
Pitching Investors & Other Nightmares
Pitching Investors & Other NightmaresPitching Investors & Other Nightmares
Pitching Investors & Other Nightmares
 
(Re)inventing software development productivity
(Re)inventing software development productivity(Re)inventing software development productivity
(Re)inventing software development productivity
 
RxJava from the trenches
RxJava from the trenchesRxJava from the trenches
RxJava from the trenches
 
Osaka Ramen
Osaka RamenOsaka Ramen
Osaka Ramen
 
ชุมนุมสหกรณ์ 22 ม ค 56
ชุมนุมสหกรณ์ 22 ม ค 56ชุมนุมสหกรณ์ 22 ม ค 56
ชุมนุมสหกรณ์ 22 ม ค 56
 

Similaire à Practices and Tools for Building Better APIs

Practices and tools for building better APIs
Practices and tools for building better APIsPractices and tools for building better APIs
Practices and tools for building better APIs
NLJUG
 

Similaire à Practices and Tools for Building Better APIs (20)

Practices and tools for building better APIs
Practices and tools for building better APIsPractices and tools for building better APIs
Practices and tools for building better APIs
 
API workshop: Introduction to APIs (TC Camp)
API workshop: Introduction to APIs (TC Camp)API workshop: Introduction to APIs (TC Camp)
API workshop: Introduction to APIs (TC Camp)
 
An Open Source Workbench for Prototyping Multimodal Interactions Based on Off...
An Open Source Workbench for Prototyping Multimodal Interactions Based on Off...An Open Source Workbench for Prototyping Multimodal Interactions Based on Off...
An Open Source Workbench for Prototyping Multimodal Interactions Based on Off...
 
API Docs with OpenAPI 3.0
API Docs with OpenAPI 3.0API Docs with OpenAPI 3.0
API Docs with OpenAPI 3.0
 
Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)
 
API Docs Made Right / RAML - Swagger rant
API Docs Made Right / RAML - Swagger rantAPI Docs Made Right / RAML - Swagger rant
API Docs Made Right / RAML - Swagger rant
 
GraphQL - The new "Lingua Franca" for API-Development
GraphQL - The new "Lingua Franca" for API-DevelopmentGraphQL - The new "Lingua Franca" for API-Development
GraphQL - The new "Lingua Franca" for API-Development
 
Building APIs in an easy way using API Platform
Building APIs in an easy way using API PlatformBuilding APIs in an easy way using API Platform
Building APIs in an easy way using API Platform
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Developing Brilliant and Powerful APIs in Ruby & Python
Developing Brilliant and Powerful APIs in Ruby & PythonDeveloping Brilliant and Powerful APIs in Ruby & Python
Developing Brilliant and Powerful APIs in Ruby & Python
 
Write Generic Code with the Tooling API
Write Generic Code with the Tooling APIWrite Generic Code with the Tooling API
Write Generic Code with the Tooling API
 
Content Strategy and Developer Engagement for DevPortals
Content Strategy and Developer Engagement for DevPortalsContent Strategy and Developer Engagement for DevPortals
Content Strategy and Developer Engagement for DevPortals
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
How to build a JavaScript toolkit
How to build a JavaScript toolkitHow to build a JavaScript toolkit
How to build a JavaScript toolkit
 
Infinum Android Talks #02 - How to write an annotation processor in Android
Infinum Android Talks #02 - How to write an annotation processor in AndroidInfinum Android Talks #02 - How to write an annotation processor in Android
Infinum Android Talks #02 - How to write an annotation processor in Android
 
APIs distribuidos con alta escalabilidad
APIs distribuidos con alta escalabilidadAPIs distribuidos con alta escalabilidad
APIs distribuidos con alta escalabilidad
 
SGCE 2015 REST APIs
SGCE 2015 REST APIsSGCE 2015 REST APIs
SGCE 2015 REST APIs
 
Introduction to Designing and Building Big Data Applications
Introduction to Designing and Building Big Data ApplicationsIntroduction to Designing and Building Big Data Applications
Introduction to Designing and Building Big Data Applications
 
Punta Dreamin 17 Generic Apex and Tooling Api
Punta Dreamin 17 Generic Apex and Tooling ApiPunta Dreamin 17 Generic Apex and Tooling Api
Punta Dreamin 17 Generic Apex and Tooling Api
 
An introduction to the API for OnTime for IBM
An introduction to the API for OnTime for IBMAn introduction to the API for OnTime for IBM
An introduction to the API for OnTime for IBM
 

Dernier

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Dernier (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 

Practices and Tools for Building Better APIs

  • 1. Practices and Tools for Building Better APIs Peter Hendriks - IT Architect, Info Support BV CON4374
  • 2. About Peter • Working at Info Support… • In a country, far, far away… • Netherlands, Europe • Coding on challenging Java applications
  • 3. Objectives of this talk • Focus on Java application developer perspective • What is an API and why should you care about it • How you can identify and build better APIs • Measuring API in an existing codebase
  • 4. What is an API • Code that is directly used to connect two software modules • “API Consumer”: module that calls the API • “API Implementer”: module that provides behavior for API public class CollectionsDemo { public static void main(String args[]) { // create an array of string objs String init[] = { "One", "Two", "Three" }; // create one list List list = new ArrayList(Arrays.asList(init)); System.out.println("List value before: "+list); // sort the list Collections.sort(list); System.out.println("List value after: "+list); } } // Load expected data from an XML dataset IDataSet expectedDataSet = new FlatXmlDataSetBuilder() .build(new File("expectedDataSet.xml")); <dataset> <PERSON NAME="Bob" LAST_NAME="Doe" AGE="18"/> <PERSON NAME="Alice" LAST_NAME="Foo" AGE="23"/> <PERSON NAME="Charlie" LAST_NAME="Brown" AGE="42"/> </dataset>
  • 5. API is key to a successful module design Essential for building large-scale software: • Reuse • Independent change • Separation of concerns Modular design key to support agile practices at scale Shared code Customer Front-End Warehouse Front-End Order Management
  • 6. You are using a lot of APIs • Modern software development relies on reuse of modules • OS, Java Platform, Libraries, Application Server, etc. • System to System APIs increasingly important • Many public APIs like Twitter, Google, Facebook, SalesForce, etc. • SOA Java SE Java EE Log4j Spring Module Module Module OS Twitter Auth Database SOA
  • 7. Distance to API implementation increasing • API quality matters more when implementation becomes a black box You Same team Different team Open source Binary only Other datacenter API Impl
  • 8. The API we use shapes our code • Most code we write calls an API • Code that calls an API is shaped to fit the API • Therefore, APIs determine the shape of application code • In some ways, even more impactful than high level design, test driven development or code craftsmanship
  • 9. http://docs.oracle.com/javaee/1.4/tutorial/examples/jaxp/xslt/samples/TransformationApp04.java public class TransformationApp04 { public static void main(String[] argv) { if (argv.length != 1) { System.err.println("Usage: java TransformationApp filename"); System.exit(1); } // Create the sax "parser". AddressBookReader02 saxReader = new AddressBookReader02(); try { File f = new File(argv[0]); // Use a Transformer for output TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); // Use the parser as a SAX source for input FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); InputSource inputSource = new InputSource(fr); SAXSource source = new SAXSource(saxReader, inputSource); StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } catch (TransformerConfigurationException tce) { // Error generated by the parser System.out.println("n** Transformer Factory error"); System.out.println(" " + tce.getMessage()); Doing stuff with XML… var json_data = JSON.stringify(obj);
  • 10. Trademarks of a better API
  • 11. Trademarks of a better API 1. Valuable (always important) • Value = benefits - costs 2. Usable (more important if used more) • Easy to learn, productive, error-proof 3. Stable (more important if used more and longer) • Able to enhance and grow features without breaking existing consumer code
  • 12. API Design == Human Interface design • Although API is for machine/machine interaction, APIs are interpreted by programmers to write the code • Programmers are humans! API is not just about capability and structural design, but also about human understanding
  • 13. API Usability quantified Generic usability model by Ben Shneiderman: • Learnability: How easy is it to accomplish basic tasks the first time? • Efficiency: Once users learned the design, how quickly can they perform tasks? • Memorability: When users return after a while, how easily can they re-establish proficiency? • Errors: How many errors do users make, how severe are these errors, and how easily can they recover from the errors? • Satisfaction: How pleasant is it to use the design?
  • 15. Designing an API: multiple perspectives public class Document { private List<Page> pages = new ArrayList<>(); public Page addPage() { Page page = new Page(); pages.add(page); page.setPageNumber(pages.size()); return page; } public void report() {...} } document.addPage().setContents("Once upon a time..."); UML: Names, Completeness, Grouping Implementation: can it be built API usage: how usable is it
  • 16. Initial design: examples first • Examples most important in API documentation • Concrete use case, usability check • Make examples exemplary • Example code will be copy-pasted • Create a cheat sheet • Improves learnability • Shows design issues Full Java EE cheat sheet on: http://www.physics.usyd.edu.au/~rennie/javaEEReferenceSheet.pdf
  • 17. When in doubt leave it out • Smaller APIs are easier to use and maintain • Less classes • Less methods • Less parameters/return values • Easier to add API later vs removing or changing it • Having a small API increases stability
  • 18. Limit API consumer code to a minimum • Some API constructs lead to verbose consumer code • Extending class/implementing interface • Checked Exception • Required casting • Required Generic Type • Hard coded parameter value • Required if, for, while, try • Required synchronization/locking
  • 19. Example: limiting logging code // classic debug call (log4j 1.x) // check debug to prevent string creation if(logger.isDebugEnabled()) { logger.debug("The new entry is " + entry + "."); } // parameterized logging (slf4j) logger.debug("The new entry is {}.", entry); public void debug(Object message) { if (isDebugEnabled()) { // .. implementation } } public void debug(String format, Object arg) { if (isDebugEnabled()) { // .. implementation } } Using Log4J API Using SLF4J API SLF4J ImplementationLog4J Implementation Better
  • 20. Java 8 Lambda expressions List<Integer> numbers = Arrays.asList(1, 2); for (int number : numbers) { if (numbers % 2 == 0) { System.out.println(number); } } forEachEven(numbers, value -> System.out.println(value)); forEachEven(numbers, new Consumer<Integer>() { public void accept(Integer value) { System.out.println(value); } }); Without Lambda expressions With Lambda Better
  • 21. Be predictable and obvious • Methods should be able to be called in any order • Constructor should only construct • Don’t have surprising side effects public class TopicListener { public TopicListener(Topic topic) { if (!topic.register(this)) throw new SystemException("error!"); } } public class TopicListener { private final Topic topic; public TopicListener(Topic topic) { this.topic = topic; } public void start() { if (!topic.register(this)) throw new SystemException("error!"); } } Better
  • 22. Predictable state • Limit the use of null as input or output • Fail fast, fail hard on wrong input public void save(String filename) { Objects.requireNonNull(filename); ... // save happens here } public void save(String filename) { if (filename == null) { return; // bad api: error is ignored! } ... // save happens here } Better
  • 23. FindBugs and JSR 305 • JSR 305: Annotations for Software Defect Detection (Dormant) • @Nonnull: may never be null • @CheckForNull: should always be checked before dereferenced • @Nullable: caller decides if null check is needed • Alternatives: Checker framework, Eclipse, IntelliJ IDEA
  • 24. FindBugs demo in Eclipse
  • 25. Investigating existing codebases • People • Team knowledge • Policy, “best practices”, conventions • Elaborate explanation necessary, “hard to do” • Bug list/exceptions/stack traces • Tools: • Finding most used API: Dependency Structure Matrix (DSM)
  • 26. Dependency Structure Matrix Document Page TextBlock Document - Page 2 - TextBlock 10 - Classes/Packages # of direct dependencies from Document to Page
  • 28. API design cheat sheet (Q & A) A Better API is: 1. Valuable 2. Usable 3. Stable API usability: • Learnability • Efficiency • Memorability • Error rate • Satisfaction API Design Perspectives: UML: names, completeness, grouping Implementation: can it be built API usage: how usable is it Examples First API Design practices: When in doubt leave it out Limit API consumer code to a minimum • Extending class/implementing interface • Checked Exception • Required casting • Required Generic Type • Hard coded parameter value • Required if, for, while, try • Required synchronization/locking Be predictable and obvious • Methods should be calleable in any order • Constructor should only construct • Don’t have surprising side effects • Limit the use of null as input or output • Fail fast, fail hard on wrong input Document Page TextBlock Document - Page 2 - TextBlock 10 - DSM: finding most used API JSR 305/FindBugs: @Nonnull: may never be null @CheckForNull: always check @Nullable: caller decides null check When API matters: • Modular design • Reuse 3rd party • Distance to impl.

Notes de l'éditeur

  1. The most important part of well-designed Java code is a nice API. A good API helps developers be more productive and write high-quality code quickly. API design matters for any developer, especially in building larger systems with a team. Modern coding tools such as Eclipse and FindBugs contain advanced tooling to help with designing an API and checking for bad usage. This session demonstrates the latest innovations, including new capabilities in Java 8, by presenting realistic examples based on real experiences in large codebases. They show that just a few Java tricks and simple annotations can make all the difference for building a great API.
  2. Who is a Java (enterprise) application developer, who is an API designer?
  3. Building software inmultipe agile teams, incremental deployment, testing.
  4. JavaOnepiechart hier?
  5. 10 minutes in
  6. * Why API&apos;s are important- API&apos;s are everywhere* JavaOne statistics- Core modular separation* Java Core, DBUnit- Shape your code* XML vs REST example* Considerations for API design+ Modular design (out of scope)+ Factory and Reporter example+ API is a lot similar to a UI design- Beauty and elegance hard to capture in rules- Pragmatic considerations and tips- Clear user goals- Examples (cheat sheets) (UML is not useful for designing an API)* Verbose coding- Control constructs (if, while, for)- Hard coded parameters- Casting and generics- Exception handling (don&apos;t use checked exceptions)* Don&apos;t be surprising- Constructors that do more- Getters with side effects* Stay focused and fit in- Cross cutting Security, logging, etc.- Java has some great standards here- Approach: interceptors* Clean modular approach- Number of methods, params- Cohesion, LCOM4 etc.- number of types in api* Tools- Null checking- Getting the numbers- Common analysis* Finding and improving- What are your most important API&apos;s? (team knowledge, defect categories, architecture)- Usage metrics- API aggregated quality index?
  7. Ben Shneiderman
  8. 20 minutes in
  9. Yuml [Document|addPage();report()]++-pages*&gt;[Page|+contents;+pageNumber]
  10. Chris Rennie from Australia
  11. 30 minutes in
  12. NamesImposed flow of control code (if, loop, cast, warnings, …)Parameter numbers/return valuesMethod orderingConstructorsExceptionsInheritanceState space (optional, nullness)GenericsDocumentation
  13. 10-15 minutes out
  14. Find most used API at the bottomFind specific relations between API and where it is usedSpot circular dependencies