SlideShare a Scribd company logo
© Asprotunity Ltd
email: gasproni@asprotunity.com
twitter: @gasproni
linkedin: http://www.linkedin.com/in/gasproni
Writing usable APIs in
practice
/dev/summer/2014
Have you been a victim of bad
APIs?
© Asprotunity Ltd
Have you written bad APIs?
© Asprotunity Ltd
© Asprotunity Ltd
When we talk about
good code we always
mean usable code as
well
© Asprotunity Ltd
API
From:“Sometimes You Need to See Through Walls — A
Field Study of Application Programming Interfaces”,
Cleidson R. B. de Souza et al., http://www.ufpa.br/
cdesouza/pub/p390-desouza.pdf
“Any well-defined interface that defines
the service that one component,
module, or application provides to
other software elements”
© Asprotunity Ltd
Example: java.io package
(Java 7)
• Interfaces: Closeable, DataInput, DataOutput, Externalizable, FileFilter, FilenameFilter, Flushable, ObjectInput,
ObjectInputValidation, ObjectOutput, ObjectStreamConstants, Serializable
• Classes: BufferedInputStream, BufferedOutputStream, BufferedReader, BufferedWriter,
ByteArrayInputStream, ByteArrayOutputStream, CharArrayReader, CharArrayWriter, Console,
DataInputStream, DataOutputStream, File, FileDescriptor, FileInputStream, FileOutputStream, FilePermission,
FileReader, FileWriter, FilterInputStream, FilterOutputStream, FilterReader, FilterWriter, InputStream,
InputStreamReader, LineNumberInputStream, LineNumberReader, ObjectInputStream,
ObjectInputStream.GetField, ObjectOutputStream, ObjectOutputStream.PutField, ObjectStreamClass,
ObjectStreamField, OutputStream, OutputStreamWriter, PipedInputStream, PipedOutputStream,
PipedReader, PipedWriter, PrintStream, PrintWriter, PushbackInputStream, PushbackReader,
RandomAccessFile, Reader, SequenceInputStream, SerializablePermission, StreamTokenizer,
StringBufferInputStream, StringReader, StringWriter, Writer
• Exceptions: CharConversionException, EOFException, FileNotFoundException, InterruptedIOException,
InvalidClassException, InvalidObjectException, IOException, NotActiveException, NotSerializableException,
ObjectStreamException, OptionalDataException, StreamCorruptedException, SyncFailedException,
UnsupportedEncodingException, UTFDataFormatException, WriteAbortedException
• Errors: IOError
© Asprotunity Ltd
Any non trivial software
application involves
writing one or more APIs
© Asprotunity Ltd
Usability
• Efficiency
• Effectiveness
• Error prevention
• Ease of learning
© Asprotunity Ltd
Giovanni’s usability equation
• u is the usability
• b > 0. The brain power necessary
to achieve your goals
• c > 0. A constant value
u =
c
b
© Asprotunity Ltd
Why bother (company’s
perspective)
• APIs can be among a company's greatest assets
• Can also be among company's greatest liabilities
Adapted from:“How to Design a Good API and Why it
Matters”, Joshua Bloch, http://lcsd05.cs.tamu.edu/slides/
keynote.pdf
© Asprotunity Ltd
Why bother (programmer’s
perspective)
• Fewer bugs to take care of
• Code of higher quality
• Solve more interesting problems
• More productivity
© Asprotunity Ltd
Public and private APIs
• Public APIs
• Given to third parties
• Private APIs
• For internal use
Some usability concepts
© Asprotunity Ltd
© Asprotunity Ltd
Affordances
An affordance is a quality of an
object, or an environment, that
allows an individual to perform
an action.
From: http://en.wikipedia.org/wiki/Affordance
© Asprotunity Ltd
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
…
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(“filename“));
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}

processLine(line);

}

}

catch (Exception exc) { 

// Do something here...

} 

finally {

if (reader != null) {

reader.close();

}

}
…
© Asprotunity Ltd
import java.nio.file.Path;
import java.nio.FileSystems;
import java.nio.charset.Charset;
…
try {
Path filePath = FileSystems.getDefault().getPath("filename");
Charset charset = Charset.defaultCharset();
for (String line : Files.readAllLines(filePath, charset)) {
processLine(line);
}
} catch (IOException e) {
// Do something here
}
…
© Asprotunity Ltd
import java.io.File;
import java.util.Scanner;
…
File file = new File("filename");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
processLine(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
…
© Asprotunity Ltd
with open("filename") as infile:
for line in infile.readlines():
processLine(line)
© Asprotunity Ltd
Some cognitive dimensions
• Abstraction level. The minimum and maximum levels of abstraction
exposed by the API
• Working framework. The size of the conceptual chunk (developer
working set) needed to work effectively
• Progressive evaluation. To what extent partially completed code can
be executed to obtain feedback on code behaviour
• Penetrability. The extent to which a developer must understand the
underlying implementation details of an API
• Consistency. How much of the rest of an API can be inferred once
part of it is learned
Adapted from:“Measuring API Usability”, Steven Clarke,
http://drdobbs.com/windows/184405654
© Asprotunity Ltd
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
…
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(“filename“));
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}

processLine(line);

}

}

catch (Exception exc) { 

// Do something here...

} 

finally {

if (reader != null) {

reader.close();

}

}
…
• Abstraction level
• Working framework
• Progressive
evaluation
• Penetrability
• Consistency
© Asprotunity Ltd
• Abstraction level
• Working framework
• Progressive
evaluation
• Penetrability
• Consistency
import java.nio.file.Path;
import java.nio.FileSystems;
import java.nio.charset.Charset;
…
try {
Path filePath = FileSystems.getDefault().getPath("filename");
Charset charset = Charset.defaultCharset();
for (String line : Files.readAllLines(filePath, charset)) {
processLine(line);
}
} catch (IOException e) {
// Do something here
}
…
© Asprotunity Ltd
• Abstraction level
• Working framework
• Progressive
evaluation
• Penetrability
• Consistency
import java.io.File;
import java.util.Scanner;
…
File file = new File("filename");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
processLine(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
…
© Asprotunity Ltd
• Abstraction level
• Working framework
• Progressive
evaluation
• Penetrability
• Consistency
with open("filename") as infile:
for line in infile.readlines():
processLine(line)
Some techniques
© Asprotunity Ltd
“None of the ideas presented here are new;
they are just forgotten from time to time.”
!
Alan J. Perlis, 1966 Turing Award Lecture.
© Asprotunity Ltd
© Asprotunity Ltd
• User’s perspective
• Naming
• Explicit context
• Error reporting
• Incremental design
© Asprotunity Ltd
• User’s perspective
• Naming
• Explicit context
• Error reporting
• Incremental design
© Asprotunity Ltd
“Ask,‘What Would the User
Do?’ (You Are Not the User)”	

!
Giles Colborne,“97 Things Every
Programmer Should Know”
Use language constructs
to make intent clear
© Asprotunity Ltd
makeTV(true, false);
© Asprotunity Ltd
From:“API Design Matters”,
Michi Henning, http://queue.acm.org/detail.cfm?
id=1255422
void makeTV(bool isColor, bool isCrt);
© Asprotunity Ltd
From:“API Design Matters”,
Michi Henning, http://queue.acm.org/detail.cfm?
id=1255422
enum ColorType { Color, BlackAndWhite }
!
enum ScreenType { CRT, FlatScreen };
void makeTV(ColorType col, ScreenType st);
© Asprotunity Ltd
From:“API Design Matters”,
Michi Henning, http://queue.acm.org/detail.cfm?
id=1255422
makeTV(Color, FlatScreen);
© Asprotunity Ltd
From:“API Design Matters”,
Michi Henning, http://queue.acm.org/detail.cfm?
id=1255422
Give control to the caller
© Asprotunity Ltd
© Asprotunity Ltd
What’s wrong with these?
public interface Startable {
Startable start() 

throws AlreadyStartedException;
}
!
public interface Stoppable {
Stoppable stop() 

throws AlreadyStoppedException;
}
© Asprotunity Ltd
A better alternative
public interface Service {
void start() 

throws AlreadyStartedException;
!
void stop() 

throws AlreadyStoppedException;
!
boolean isStarted();
}
© Asprotunity Ltd
TDD
• It puts you in the shoes of an user
• Outside-in development
• If writing a test is painful, the design may be wrong
• Tests will provide up to date documentation and
examples of use
© Asprotunity Ltd
TDD helps with
• Abstraction level. It helps to limit the number of
abstractions in mainline scenarios
• Working framework. It helps in keeping it smaller
• Progressive evaluation. The tests themselves are written
in a progressive way
• Penetrability. It provides examples on how the various
components interact with each other
• Consistency. It is maintained by refactoring the code
© Asprotunity Ltd
Back to the first example:
potential test with TDD
…
List<String> expectedLines = …;
File file = new File(“testfile“));
assertEquals(file.readLines(), expectedLines);

…
More likely outcome
© Asprotunity Ltd
File file = new File(“filename“));
try {
for (String line : file.readLines()) {
processLine(line);
}

}
finally { 

file.close()

}
© Asprotunity Ltd
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(“filename“));
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}

processLine(line);

}

}

catch (Exception exc) { 

// Do something here...

} 

finally {

if (reader != null) {

reader.close();

}

}
Less likely outcome
© Asprotunity Ltd
• User’s perspective
• Naming
• Explicit context
• Error reporting
• Incremental design
"There are only two hard problems in
Computer Science: cache invalidation,
naming things and off-by-one errors.”
!
Variation on a Phil Karlton quote
© Asprotunity Ltd
© Asprotunity Ltd
Naming
• Reserve the simplest and most intuitive names for
the entities used in the most common scenarios
• Pick one word per concept
• Use easy to remember conventions
• Don’t be cute!
© Asprotunity Ltd
What not to do (1/2)
• java.io.ObjectStreamConstants
• Constants written into the Object Serialization
Stream
© Asprotunity Ltd
© Asprotunity Ltd
• User’s perspective
• Naming
• Explicit context
• Error reporting
• Incremental design
© Asprotunity Ltd
Explicit context
• Assumptions about the external environment
• There are two kinds of context we are interested in
• Deployment context
• Runtime context
© Asprotunity Ltd
Deployment context
• Dependencies on other APIs
• Assumptions on deployment paths
• User permissions
• etc.
© Asprotunity Ltd
Runtime context
• Initialization (and finalization) steps
• Preconditions for calling methods (or functions) or
instantiating classes
• Assumptions about global application state
© Asprotunity Ltd
Global state
• Difficult to use in a concurrent environment
• Can make test setup extremely hard
• Can make penetrability really hard by hiding
dependencies
© Asprotunity Ltd
• User’s perspective
• Naming
• Explicit context
• Error reporting
• Incremental design
© Asprotunity Ltd
Error reporting
• Error reporting code is important for usability
• Users need to know
• How errors are reported
• What is reported when
• What they can do about them
© Asprotunity Ltd
Error recovery
• Make recovery easy to do
• Error codes
• Exception classes
• A mix of the above
• Text messages are usually not good enough
Error management and
reporting need careful design
from the very beginning
© Asprotunity Ltd
© Asprotunity Ltd
What is an error at one
level....
...May not be an error
at another one
© Asprotunity Ltd
• User’s perspective
• Naming
• Explicit context
• Error reporting
• Incremental design
© Asprotunity Ltd
I will contend that conceptual integrity
is the most important consideration in
system design. It is better to have a
system omit certain anomalous features
and improvements, but to reflect one
set of design ideas, than to have one
that contains many good but
independent and uncoordinated ideas.
!
Fred Brooks,“The Mythical Man Month”
ptg6931361
From the Library of Giovanni Asproni
© Asprotunity Ltd
Start specific and small
• Start with the 80% case first
• It is easier to remove constraints rather than to add
them later
• YAGNI
© Asprotunity Ltd
A caveat
• Public APIs are more difficult to refactor. In fact,
some errors may actually become features
• Techniques to refactor them usually involve some
form of deprecation and versioning
Surprising study results
© Asprotunity Ltd
© Asprotunity Ltd
A user study comparing the usability of the factory
pattern and constructors in API designs found highly
significant results indicating that factories are
detrimental to API usability in several varied situations.
The results showed that users require significantly more
time (p = 0.005) to construct an object with a factory
than with a constructor while performing both context-
sensitive and context free tasks
From:“The Factory Pattern in API Design: A Usability
Evaluation”
Factory pattern
© Asprotunity Ltd
It was hypothesized that required parameters would create
more usable and self documenting APIs by guiding
programmers toward the correct use of objects and preventing
errors. However, in the study, it was found that, contrary to
expectations, programmers strongly preferred and were
more effective with APIs that did not require constructor
parameters. Participants’behavior was analyzed using the
cognitive dimensions framework, and revealing that required
constructor parameters interfere with common learning
strategies, causing undesirable premature commitment.
!
From:“Usability Implications of Requiring Parameters in
Objects’Constructors”
Constructors
© Asprotunity Ltd
Conclusion
• User’s perspective
• Naming
• Explicit context
• Error reporting
• Incremental design
© Asprotunity Ltd
Links
• http://www.apiusability.org
• “Sometimes You Need to See Through Walls — A Field Study of Application Programming Interfaces”, Cleidson R.
B. de Souza et al., http://www.ufpa.br/cdesouza/pub/p390-desouza.pdf
• “Measuring API Usability”, Steven Clarke, http://drdobbs.com/windows/184405654
• “API Design Matters”, Michi Henning, http://queue.acm.org/detail.cfm?id=1255422
• http://en.wikipedia.org/wiki/Affordance
• “How to Design a Good API and Why it Matters”, Joshua Bloch, http://lcsd05.cs.tamu.edu/slides/keynote.pdf
• “What Makes APIs Difficult to Use?”, Minhaz Fahim Zibran, http://paper.ijcsns.org/07_book/200804/20080436.pdf
• http://www.codeproject.com/Articles/8707/API-Usability-Guidelines-to-improve-your-code-ease
• “Usability Implications of Requiring Parameters in Objects’Constructors”, Jeffrey Stylos and Steven Clarke, http://
www.cs.cmu.edu/~NatProg/papers/Stylos2007CreateSetCall.pdf
• “The Factory Pattern in API Design: A Usability Evaluation”, Brian Ellis, Jeffrey Stylos, and Brad Myers, http://
www.cs.cmu.edu/~NatProg/papers/Ellis2007FactoryUsability.pdf
© Asprotunity Ltd
Books
ptg6931361
From the Library of Giovanni Asproni

More Related Content

What's hot

Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Code
erikmsp
 
Testing untestable code - PHPBNL11
Testing untestable code - PHPBNL11Testing untestable code - PHPBNL11
Testing untestable code - PHPBNL11
Stephan Hochdörfer
 
Real world dependency injection - DPC10
Real world dependency injection - DPC10Real world dependency injection - DPC10
Real world dependency injection - DPC10
Stephan Hochdörfer
 

What's hot (20)

Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Code
 
Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018
 
Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design of Existing Software
 
Hotfixing iOS apps with Javascript
Hotfixing iOS apps with JavascriptHotfixing iOS apps with Javascript
Hotfixing iOS apps with Javascript
 
Java 7 - What's New?
Java 7 - What's New?Java 7 - What's New?
Java 7 - What's New?
 
The Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignThe Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable Design
 
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
 
Testing untestable code - PHPBNL11
Testing untestable code - PHPBNL11Testing untestable code - PHPBNL11
Testing untestable code - PHPBNL11
 
PVS-Studio and CppCat: An Interview with Andrey Karpov, the Project CTO and D...
PVS-Studio and CppCat: An Interview with Andrey Karpov, the Project CTO and D...PVS-Studio and CppCat: An Interview with Andrey Karpov, the Project CTO and D...
PVS-Studio and CppCat: An Interview with Andrey Karpov, the Project CTO and D...
 
StdAfx.h for Novices
StdAfx.h for NovicesStdAfx.h for Novices
StdAfx.h for Novices
 
The Art of Metaprogramming in Java
The Art of Metaprogramming in Java  The Art of Metaprogramming in Java
The Art of Metaprogramming in Java
 
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
 
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
 
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
 
Real world dependency injection - DPC10
Real world dependency injection - DPC10Real world dependency injection - DPC10
Real world dependency injection - DPC10
 
The State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediThe State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila Szegedi
 
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
 
Testing untestable code - DPC10
Testing untestable code - DPC10Testing untestable code - DPC10
Testing untestable code - DPC10
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails Apps
 

Similar to Writing usableap isinpractice

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
 

Similar to Writing usableap isinpractice (20)

Java 7 & 8 New Features
Java 7 & 8 New FeaturesJava 7 & 8 New Features
Java 7 & 8 New Features
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Seven perilous pitfalls to avoid with Java | DevNation Tech Talk
Seven perilous pitfalls to avoid with Java | DevNation Tech TalkSeven perilous pitfalls to avoid with Java | DevNation Tech Talk
Seven perilous pitfalls to avoid with Java | DevNation Tech Talk
 
Apache Beam de A à Z
 Apache Beam de A à Z Apache Beam de A à Z
Apache Beam de A à Z
 
Java 8 Overview
Java 8 OverviewJava 8 Overview
Java 8 Overview
 
Building JBoss AS 7 for Fedora
Building JBoss AS 7 for FedoraBuilding JBoss AS 7 for Fedora
Building JBoss AS 7 for Fedora
 
It's always your fault
It's always your faultIt's always your fault
It's always your fault
 
Lambdas & Streams
Lambdas & StreamsLambdas & Streams
Lambdas & Streams
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
Scala for Test Automation
Scala for Test AutomationScala for Test Automation
Scala for Test Automation
 
OSGi Enterprise R6 specs are out! - David Bosschaert & Carsten Ziegeler
OSGi Enterprise R6 specs are out! - David Bosschaert & Carsten ZiegelerOSGi Enterprise R6 specs are out! - David Bosschaert & Carsten Ziegeler
OSGi Enterprise R6 specs are out! - David Bosschaert & Carsten Ziegeler
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
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
 
Practices and tools for building better API (JFall 2013)
Practices and tools for building better API (JFall 2013)Practices and tools for building better API (JFall 2013)
Practices and tools for building better API (JFall 2013)
 
Cocoapods and Most common used library in Swift
Cocoapods and Most common used library in SwiftCocoapods and Most common used library in Swift
Cocoapods and Most common used library in Swift
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
 
Java Notes
Java Notes Java Notes
Java Notes
 
Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2
 

More from Giovanni Asproni

More from Giovanni Asproni (9)

Remote Mob Programming In A High Stakes Environment (Agile Manchester 2023)
Remote Mob Programming In A High Stakes Environment (Agile Manchester 2023)Remote Mob Programming In A High Stakes Environment (Agile Manchester 2023)
Remote Mob Programming In A High Stakes Environment (Agile Manchester 2023)
 
Remote mobprogrammingina highstakesenvironment
Remote mobprogrammingina highstakesenvironmentRemote mobprogrammingina highstakesenvironment
Remote mobprogrammingina highstakesenvironment
 
Creating An Incremental Architecture For Your System
Creating An Incremental Architecture For Your SystemCreating An Incremental Architecture For Your System
Creating An Incremental Architecture For Your System
 
Scaling Agile Done Right (XP 2017 version)
Scaling Agile Done Right (XP 2017 version)Scaling Agile Done Right (XP 2017 version)
Scaling Agile Done Right (XP 2017 version)
 
Scaling Agile Done Right (Agile Manchester 2017)
Scaling Agile Done Right (Agile Manchester 2017)Scaling Agile Done Right (Agile Manchester 2017)
Scaling Agile Done Right (Agile Manchester 2017)
 
Creating An Incremental Architecture For Your System
Creating An Incremental Architecture For Your SystemCreating An Incremental Architecture For Your System
Creating An Incremental Architecture For Your System
 
Design For Testability
Design For TestabilityDesign For Testability
Design For Testability
 
Faking Hell
Faking HellFaking Hell
Faking Hell
 
Methodology Patterns (Agile Cambridge 2014)
Methodology Patterns (Agile Cambridge 2014)Methodology Patterns (Agile Cambridge 2014)
Methodology Patterns (Agile Cambridge 2014)
 

Recently uploaded

Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 

Recently uploaded (20)

Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 

Writing usableap isinpractice

  • 1. © Asprotunity Ltd email: gasproni@asprotunity.com twitter: @gasproni linkedin: http://www.linkedin.com/in/gasproni Writing usable APIs in practice /dev/summer/2014
  • 2. Have you been a victim of bad APIs? © Asprotunity Ltd
  • 3. Have you written bad APIs? © Asprotunity Ltd
  • 4. © Asprotunity Ltd When we talk about good code we always mean usable code as well
  • 5. © Asprotunity Ltd API From:“Sometimes You Need to See Through Walls — A Field Study of Application Programming Interfaces”, Cleidson R. B. de Souza et al., http://www.ufpa.br/ cdesouza/pub/p390-desouza.pdf “Any well-defined interface that defines the service that one component, module, or application provides to other software elements”
  • 6. © Asprotunity Ltd Example: java.io package (Java 7) • Interfaces: Closeable, DataInput, DataOutput, Externalizable, FileFilter, FilenameFilter, Flushable, ObjectInput, ObjectInputValidation, ObjectOutput, ObjectStreamConstants, Serializable • Classes: BufferedInputStream, BufferedOutputStream, BufferedReader, BufferedWriter, ByteArrayInputStream, ByteArrayOutputStream, CharArrayReader, CharArrayWriter, Console, DataInputStream, DataOutputStream, File, FileDescriptor, FileInputStream, FileOutputStream, FilePermission, FileReader, FileWriter, FilterInputStream, FilterOutputStream, FilterReader, FilterWriter, InputStream, InputStreamReader, LineNumberInputStream, LineNumberReader, ObjectInputStream, ObjectInputStream.GetField, ObjectOutputStream, ObjectOutputStream.PutField, ObjectStreamClass, ObjectStreamField, OutputStream, OutputStreamWriter, PipedInputStream, PipedOutputStream, PipedReader, PipedWriter, PrintStream, PrintWriter, PushbackInputStream, PushbackReader, RandomAccessFile, Reader, SequenceInputStream, SerializablePermission, StreamTokenizer, StringBufferInputStream, StringReader, StringWriter, Writer • Exceptions: CharConversionException, EOFException, FileNotFoundException, InterruptedIOException, InvalidClassException, InvalidObjectException, IOException, NotActiveException, NotSerializableException, ObjectStreamException, OptionalDataException, StreamCorruptedException, SyncFailedException, UnsupportedEncodingException, UTFDataFormatException, WriteAbortedException • Errors: IOError
  • 7. © Asprotunity Ltd Any non trivial software application involves writing one or more APIs
  • 8. © Asprotunity Ltd Usability • Efficiency • Effectiveness • Error prevention • Ease of learning
  • 9. © Asprotunity Ltd Giovanni’s usability equation • u is the usability • b > 0. The brain power necessary to achieve your goals • c > 0. A constant value u = c b
  • 10. © Asprotunity Ltd Why bother (company’s perspective) • APIs can be among a company's greatest assets • Can also be among company's greatest liabilities Adapted from:“How to Design a Good API and Why it Matters”, Joshua Bloch, http://lcsd05.cs.tamu.edu/slides/ keynote.pdf
  • 11. © Asprotunity Ltd Why bother (programmer’s perspective) • Fewer bugs to take care of • Code of higher quality • Solve more interesting problems • More productivity
  • 12. © Asprotunity Ltd Public and private APIs • Public APIs • Given to third parties • Private APIs • For internal use
  • 13. Some usability concepts © Asprotunity Ltd
  • 14. © Asprotunity Ltd Affordances An affordance is a quality of an object, or an environment, that allows an individual to perform an action. From: http://en.wikipedia.org/wiki/Affordance
  • 15. © Asprotunity Ltd import java.io.BufferedReader; import java.io.File; import java.io.FileReader; … BufferedReader reader; try { reader = new BufferedReader(new FileReader(“filename“)); while (true) { String line = reader.readLine(); if (line == null) { break; }
 processLine(line);
 }
 }
 catch (Exception exc) { 
 // Do something here...
 } 
 finally {
 if (reader != null) {
 reader.close();
 }
 } …
  • 16. © Asprotunity Ltd import java.nio.file.Path; import java.nio.FileSystems; import java.nio.charset.Charset; … try { Path filePath = FileSystems.getDefault().getPath("filename"); Charset charset = Charset.defaultCharset(); for (String line : Files.readAllLines(filePath, charset)) { processLine(line); } } catch (IOException e) { // Do something here } …
  • 17. © Asprotunity Ltd import java.io.File; import java.util.Scanner; … File file = new File("filename"); try { Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); processLine(line); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } …
  • 18. © Asprotunity Ltd with open("filename") as infile: for line in infile.readlines(): processLine(line)
  • 19. © Asprotunity Ltd Some cognitive dimensions • Abstraction level. The minimum and maximum levels of abstraction exposed by the API • Working framework. The size of the conceptual chunk (developer working set) needed to work effectively • Progressive evaluation. To what extent partially completed code can be executed to obtain feedback on code behaviour • Penetrability. The extent to which a developer must understand the underlying implementation details of an API • Consistency. How much of the rest of an API can be inferred once part of it is learned Adapted from:“Measuring API Usability”, Steven Clarke, http://drdobbs.com/windows/184405654
  • 20. © Asprotunity Ltd import java.io.BufferedReader; import java.io.File; import java.io.FileReader; … BufferedReader reader; try { reader = new BufferedReader(new FileReader(“filename“)); while (true) { String line = reader.readLine(); if (line == null) { break; }
 processLine(line);
 }
 }
 catch (Exception exc) { 
 // Do something here...
 } 
 finally {
 if (reader != null) {
 reader.close();
 }
 } … • Abstraction level • Working framework • Progressive evaluation • Penetrability • Consistency
  • 21. © Asprotunity Ltd • Abstraction level • Working framework • Progressive evaluation • Penetrability • Consistency import java.nio.file.Path; import java.nio.FileSystems; import java.nio.charset.Charset; … try { Path filePath = FileSystems.getDefault().getPath("filename"); Charset charset = Charset.defaultCharset(); for (String line : Files.readAllLines(filePath, charset)) { processLine(line); } } catch (IOException e) { // Do something here } …
  • 22. © Asprotunity Ltd • Abstraction level • Working framework • Progressive evaluation • Penetrability • Consistency import java.io.File; import java.util.Scanner; … File file = new File("filename"); try { Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); processLine(line); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } …
  • 23. © Asprotunity Ltd • Abstraction level • Working framework • Progressive evaluation • Penetrability • Consistency with open("filename") as infile: for line in infile.readlines(): processLine(line)
  • 25. “None of the ideas presented here are new; they are just forgotten from time to time.” ! Alan J. Perlis, 1966 Turing Award Lecture. © Asprotunity Ltd
  • 26. © Asprotunity Ltd • User’s perspective • Naming • Explicit context • Error reporting • Incremental design
  • 27. © Asprotunity Ltd • User’s perspective • Naming • Explicit context • Error reporting • Incremental design
  • 28. © Asprotunity Ltd “Ask,‘What Would the User Do?’ (You Are Not the User)” ! Giles Colborne,“97 Things Every Programmer Should Know”
  • 29. Use language constructs to make intent clear © Asprotunity Ltd
  • 30. makeTV(true, false); © Asprotunity Ltd From:“API Design Matters”, Michi Henning, http://queue.acm.org/detail.cfm? id=1255422
  • 31. void makeTV(bool isColor, bool isCrt); © Asprotunity Ltd From:“API Design Matters”, Michi Henning, http://queue.acm.org/detail.cfm? id=1255422
  • 32. enum ColorType { Color, BlackAndWhite } ! enum ScreenType { CRT, FlatScreen }; void makeTV(ColorType col, ScreenType st); © Asprotunity Ltd From:“API Design Matters”, Michi Henning, http://queue.acm.org/detail.cfm? id=1255422
  • 33. makeTV(Color, FlatScreen); © Asprotunity Ltd From:“API Design Matters”, Michi Henning, http://queue.acm.org/detail.cfm? id=1255422
  • 34. Give control to the caller © Asprotunity Ltd
  • 35. © Asprotunity Ltd What’s wrong with these? public interface Startable { Startable start() 
 throws AlreadyStartedException; } ! public interface Stoppable { Stoppable stop() 
 throws AlreadyStoppedException; }
  • 36. © Asprotunity Ltd A better alternative public interface Service { void start() 
 throws AlreadyStartedException; ! void stop() 
 throws AlreadyStoppedException; ! boolean isStarted(); }
  • 37. © Asprotunity Ltd TDD • It puts you in the shoes of an user • Outside-in development • If writing a test is painful, the design may be wrong • Tests will provide up to date documentation and examples of use
  • 38. © Asprotunity Ltd TDD helps with • Abstraction level. It helps to limit the number of abstractions in mainline scenarios • Working framework. It helps in keeping it smaller • Progressive evaluation. The tests themselves are written in a progressive way • Penetrability. It provides examples on how the various components interact with each other • Consistency. It is maintained by refactoring the code
  • 39. © Asprotunity Ltd Back to the first example: potential test with TDD … List<String> expectedLines = …; File file = new File(“testfile“)); assertEquals(file.readLines(), expectedLines);
 …
  • 40. More likely outcome © Asprotunity Ltd File file = new File(“filename“)); try { for (String line : file.readLines()) { processLine(line); }
 } finally { 
 file.close()
 }
  • 41. © Asprotunity Ltd BufferedReader reader; try { reader = new BufferedReader(new FileReader(“filename“)); while (true) { String line = reader.readLine(); if (line == null) { break; }
 processLine(line);
 }
 }
 catch (Exception exc) { 
 // Do something here...
 } 
 finally {
 if (reader != null) {
 reader.close();
 }
 } Less likely outcome
  • 42. © Asprotunity Ltd • User’s perspective • Naming • Explicit context • Error reporting • Incremental design
  • 43. "There are only two hard problems in Computer Science: cache invalidation, naming things and off-by-one errors.” ! Variation on a Phil Karlton quote © Asprotunity Ltd
  • 44. © Asprotunity Ltd Naming • Reserve the simplest and most intuitive names for the entities used in the most common scenarios • Pick one word per concept • Use easy to remember conventions • Don’t be cute!
  • 45. © Asprotunity Ltd What not to do (1/2) • java.io.ObjectStreamConstants • Constants written into the Object Serialization Stream
  • 47. © Asprotunity Ltd • User’s perspective • Naming • Explicit context • Error reporting • Incremental design
  • 48. © Asprotunity Ltd Explicit context • Assumptions about the external environment • There are two kinds of context we are interested in • Deployment context • Runtime context
  • 49. © Asprotunity Ltd Deployment context • Dependencies on other APIs • Assumptions on deployment paths • User permissions • etc.
  • 50. © Asprotunity Ltd Runtime context • Initialization (and finalization) steps • Preconditions for calling methods (or functions) or instantiating classes • Assumptions about global application state
  • 51. © Asprotunity Ltd Global state • Difficult to use in a concurrent environment • Can make test setup extremely hard • Can make penetrability really hard by hiding dependencies
  • 52. © Asprotunity Ltd • User’s perspective • Naming • Explicit context • Error reporting • Incremental design
  • 53. © Asprotunity Ltd Error reporting • Error reporting code is important for usability • Users need to know • How errors are reported • What is reported when • What they can do about them
  • 54. © Asprotunity Ltd Error recovery • Make recovery easy to do • Error codes • Exception classes • A mix of the above • Text messages are usually not good enough
  • 55. Error management and reporting need careful design from the very beginning © Asprotunity Ltd
  • 56. © Asprotunity Ltd What is an error at one level.... ...May not be an error at another one
  • 57. © Asprotunity Ltd • User’s perspective • Naming • Explicit context • Error reporting • Incremental design
  • 58. © Asprotunity Ltd I will contend that conceptual integrity is the most important consideration in system design. It is better to have a system omit certain anomalous features and improvements, but to reflect one set of design ideas, than to have one that contains many good but independent and uncoordinated ideas. ! Fred Brooks,“The Mythical Man Month” ptg6931361 From the Library of Giovanni Asproni
  • 59. © Asprotunity Ltd Start specific and small • Start with the 80% case first • It is easier to remove constraints rather than to add them later • YAGNI
  • 60. © Asprotunity Ltd A caveat • Public APIs are more difficult to refactor. In fact, some errors may actually become features • Techniques to refactor them usually involve some form of deprecation and versioning
  • 61. Surprising study results © Asprotunity Ltd
  • 62. © Asprotunity Ltd A user study comparing the usability of the factory pattern and constructors in API designs found highly significant results indicating that factories are detrimental to API usability in several varied situations. The results showed that users require significantly more time (p = 0.005) to construct an object with a factory than with a constructor while performing both context- sensitive and context free tasks From:“The Factory Pattern in API Design: A Usability Evaluation” Factory pattern
  • 63. © Asprotunity Ltd It was hypothesized that required parameters would create more usable and self documenting APIs by guiding programmers toward the correct use of objects and preventing errors. However, in the study, it was found that, contrary to expectations, programmers strongly preferred and were more effective with APIs that did not require constructor parameters. Participants’behavior was analyzed using the cognitive dimensions framework, and revealing that required constructor parameters interfere with common learning strategies, causing undesirable premature commitment. ! From:“Usability Implications of Requiring Parameters in Objects’Constructors” Constructors
  • 64. © Asprotunity Ltd Conclusion • User’s perspective • Naming • Explicit context • Error reporting • Incremental design
  • 65. © Asprotunity Ltd Links • http://www.apiusability.org • “Sometimes You Need to See Through Walls — A Field Study of Application Programming Interfaces”, Cleidson R. B. de Souza et al., http://www.ufpa.br/cdesouza/pub/p390-desouza.pdf • “Measuring API Usability”, Steven Clarke, http://drdobbs.com/windows/184405654 • “API Design Matters”, Michi Henning, http://queue.acm.org/detail.cfm?id=1255422 • http://en.wikipedia.org/wiki/Affordance • “How to Design a Good API and Why it Matters”, Joshua Bloch, http://lcsd05.cs.tamu.edu/slides/keynote.pdf • “What Makes APIs Difficult to Use?”, Minhaz Fahim Zibran, http://paper.ijcsns.org/07_book/200804/20080436.pdf • http://www.codeproject.com/Articles/8707/API-Usability-Guidelines-to-improve-your-code-ease • “Usability Implications of Requiring Parameters in Objects’Constructors”, Jeffrey Stylos and Steven Clarke, http:// www.cs.cmu.edu/~NatProg/papers/Stylos2007CreateSetCall.pdf • “The Factory Pattern in API Design: A Usability Evaluation”, Brian Ellis, Jeffrey Stylos, and Brad Myers, http:// www.cs.cmu.edu/~NatProg/papers/Ellis2007FactoryUsability.pdf
  • 66. © Asprotunity Ltd Books ptg6931361 From the Library of Giovanni Asproni