SlideShare a Scribd company logo
1 of 49
Download to read offline
How to Design a Good
    API and Why it Matters



      Joshua Bloch
      Principal Software Engineer

    _How   to Design a Good API and Why it Matters
1
Why is API Design Important?


    • APIs can be among a company's greatest assets
            _ Customers invest heavily: buying, writing, learning
            _ Cost to stop using an API can be prohibitive
            _ Successful public APIs capture customers

    • Can also be among company's greatest liabilities
            _ Bad APIs result in unending stream of support calls

    • Public APIs are forever - one chance to get it right



    _How   to Design a Good API and Why it Matters
2
Why is API Design Important to You?

    • If you program, you are an API designer
            _ Good code is modular–each module has an API

    • Useful modules tend to get reused
            _ Once module has users, can’t change API at will
            _ Good reusable modules are corporate assets

    • Thinking in terms of APIs improves code quality




    _How   to Design a Good API and Why it Matters
3
Characteristics of a Good API

    •      Easy to learn
    •      Easy to use, even without documentation
    •      Hard to misuse
    •      Easy to read and maintain code that uses it
    •      Sufficiently powerful to satisfy requirements
    •      Easy to extend
    •      Appropriate to audience



    _How   to Design a Good API and Why it Matters
4
Outline

       I. The Process of API Design
      II. General Principles
     III. Class Design
     IV. Method Design
      V. Exception Design
     VI. Refactoring API Designs




    _How   to Design a Good API and Why it Matters
5
I. The Process of API Design




    _How   to Design a Good API and Why it Matters
6
Gather Requirements–with a Healthy
    Degree of Skepticism

    • Often you'll get proposed solutions instead
            _ Better solutions may exist

    • Your job is to extract true requirements
            _ Should take the form of use-cases

    • Can be easier and more rewarding to build
           something more general


                 Good
    _How   to Design a Good API and Why it Matters
7
Start with Short Spec–1 Page is Ideal

    • At this stage, agility trumps completeness
    • Bounce spec off as many people as possible
            _ Listen to their input and take it seriously

    • If you keep the spec short, it’s easy to modify
    • Flesh it out as you gain confidence
            _ This necessarily involves coding




    _How   to Design a Good API and Why it Matters
8
Write to Your API Early and Often

    • Start before you've implemented the API
            _ Saves you doing implementation you'll throw away

    • Start before you've even specified it properly
            _ Saves you from writing specs you'll throw away

    • Continue writing to API as you flesh it out
            _ Prevents nasty surprises
            _ Code lives on as examples, unit tests




    _How   to Design a Good API and Why it Matters
9
Writing to SPI is Even More Important


     • Service Provider Interface (SPI)
             _ Plug-in interface enabling multiple implementations
             _ Example: Java Cryptography Extension (JCE)
     • Write multiple plug-ins before release
             _ If you write one, it probably won't support another
             _ If you write two, it will support more with difficulty
             _ If you write three, it will work fine
     • Will Tracz calls this “The Rule of Threes”
            (Confessions of a Used Program Salesman, Addison-Wesley, 1995)



                    Bad
     _How   to Design a Good API and Why it Matters
10
Maintain Realistic Expectations

     • Most API designs are over-constrained
             _ You won't be able to please everyone
             _ Aim to displease everyone equally

     • Expect to make mistakes
             _ A few years of real-world use will flush them out
             _ Expect to evolve API




     _How   to Design a Good API and Why it Matters
11
II. General Principles



     _How   to Design a Good API and Why it Matters
12
API Should Do One Thing and Do it Well


     • Functionality should be easy to explain
             _ If it's hard to name, that's generally a bad sign
             _ Good names drive development
             _ Be amenable to splitting and merging modules




     _How   to Design a Good API and Why it Matters
13
API Should Be As Small As Possible But
     No Smaller

     • API should satisfy its requirements
     • When in doubt leave it out
             _ Functionality, classes, methods, parameters, etc.
             _ You can always add, but you can never remove

     • Conceptual weight more important than bulk
     • Look for a good power-to-weight ratio



     _How   to Design a Good API and Why it Matters
14
Implementation Should Not Impact API

     • Implementation details
             _ Confuse users
             _ Inhibit freedom to change implementation
     • Be aware of what is an implementation detail
             _ Do not overspecify the behavior of methods
             _ For example: do not specify hash functions
             _ All tuning parameters are suspect
     • Don't let implementation details “leak” into API
             _ On-disk and on-the-wire formats, exceptions



     _How   to Design a Good API and Why it Matters
15
Minimize Accessibility of Everything

     • Make classes and members as private as possible
     • Public classes should have no public fields
            (with the exception of constants)

     • This maximizes information hiding
     • Allows modules to be used, understood, built,
            tested, and debugged independently




     _How   to Design a Good API and Why it Matters
16
Names Matter–API is a Little Language


     • Names Should Be Largely Self-Explanatory
             _ Avoid cryptic abbreviations
     • Be consistent–same word means same thing
             _ Throughout API, (Across APIs on the platform)
     • Be regular–strive for symmetry
     • Code should read like prose
        if (car.speed() > 2 * SPEED_LIMIT)
           generateAlert(quot;Watch out for cops!quot;);




     _How   to Design a Good API and Why it Matters
17
Documentation Matters

     Reuse is something that is far easier to say than
     to do. Doing it requires both good design and
     very good documentation. Even when we see
     good design, which is still infrequently, we won't
     see the components reused without good
     documentation.
                - D. L. Parnas, _Software Aging. Proceedings
                  of 16th International Conference Software
                 Engineering, 1994



     _How   to Design a Good API and Why it Matters
18
Document Religiously

     • Document every class, interface, method,
            constructor, parameter, and exception
             _ Class: what an instance represents
             _ Method: contract between method and its client
                      _ Preconditions, postconditions, side-effects
             _ Parameter: indicate units, form, ownership

     • Document state space very carefully




     _How   to Design a Good API and Why it Matters
19
Consider Performance Consequences of
     API Design Decisions

     • Bad decisions can limit performance
             _ Making type mutable
             _ Providing constructor instead of static factory
             _ Using implementation type instead of interface
     • Do not warp API to gain performance
             _ Underlying performance issue will get fixed,
               but headaches will be with you forever
             _ Good design usually coincides with good performance




     _How   to Design a Good API and Why it Matters
20
Effects of API Design Decisions on
     Performance are Real and Permanent

     • Component.getSize() returns Dimension
     • Dimension is mutable
     • Each getSize call must allocate Dimension
     • Causes millions of needless object allocations
     • Alternative added in 1.2; old client code still slow




     _How   to Design a Good API and Why it Matters
21
API Must Coexist Peacefully with Platform

     • Do what is customary
             _ Obey standard naming conventions
             _ Avoid obsolete parameter and return types
             _ Mimic patterns in core APIs and language
     • Take advantage of API-friendly features
             _ Generics, varargs, enums, default arguments
     • Know and avoid API traps and pitfalls
             _ Finalizers, public static final arrays




     _How   to Design a Good API and Why it Matters
22
III. Class Design



     _How   to Design a Good API and Why it Matters
23
Minimize Mutability

     • Classes should be immutable unless there’s a
            good reason to do otherwise
             _ Advantages: simple, thread-safe, reusable
             _ Disadvantage: separate object for each value
     • If mutable, keep state-space small, well-defined
             _ Make clear when it's legal to call which method
     Bad: Date, Calendar
     Good: TimerTask



     _How   to Design a Good API and Why it Matters
24
Subclass Only Where It Makes Sense


     • Subclassing implies substitutability (Liskov)
             _ Subclass only when is-a relationship exists
             _ Otherwise, use composition
     • Public classes should not subclass other public
            classes for ease of implementation
     Bad:                   Properties extends Hashtable
                            Stack extends Vector
     Good: Set extends Collection



     _How   to Design a Good API and Why it Matters
25
Design and Document for Inheritance
     or Else Prohibit it

     • Inheritance violates encapsulation (Snyder, ‘86)
             _ Subclass sensitive to implementation details of
               superclass
     • If you allow subclassing, document self-use
             _ How do methods use one another?
     • Conservative policy: all concrete classes final
     Bad: Many concrete classes in J2SE libraries
     Good: AbstractSet, AbstractMap



     _How   to Design a Good API and Why it Matters
26
IV. Method Design



     _How   to Design a Good API and Why it Matters
27
Don't Make the Client Do Anything the
     Module Could Do

     • Reduce need for boilerplate code
             _ Generally done via cut-and-paste
             _ Ugly, annoying, and error-prone
       import       org.w3c.dom.*;
       import       java.io.*;
       import       javax.xml.transform.*;
       import       javax.xml.transform.dom.*;
       import       javax.xml.transform.stream.*;

       // DOM code to write an XML document to a specified output stream.
       private static final void writeDoc(Document doc, OutputStream out)throws IOException{
         try {
           Transformer t = TransformerFactory.newInstance().newTransformer();
           t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId());
           t.transform(new DOMSource(doc), new StreamResult(out));
         } catch(TransformerException e) {
           throw new AssertionError(e); // Can’t happen!
         }
       }




     _How   to Design a Good API and Why it Matters
28
Don't Violate the Principle of Least
     Astonishment

     • User of API should not be surprised by behavior
             _ It's worth extra implementation effort
             _ It's even worth reduced performance

        public class Thread implements Runnable {
          // Tests whether current thread has been interrupted.
          // Clears the interrupted status of current thread.
          public static boolean interrupted();
        }




     _How   to Design a Good API and Why it Matters
29
Fail Fast–Report Errors as Soon as
     Possible After They Occur

     • Compile time is best - static typing, generics
     • At runtime, first bad method invocation is best
             _ Method should be failure-atomic
        // A Properties instance maps strings to strings
        public class Properties extends Hashtable {
           public Object put(Object key, Object value);

                 // Throws ClassCastException if this properties
                 // contains any keys or values that are not strings
                 public void save(OutputStream out, String comments);
        }




     _How   to Design a Good API and Why it Matters
30
Provide Programmatic Access to All
     Data Available in String Form

     • Otherwise, clients will parse strings
             _ Painful for clients
             _ Worse, turns string format into de facto API
     public class Throwable {
       public void printStackTrace(PrintStream s);
       public StackTraceElement[] getStackTrace(); // Since 1.4
     }
     public final class StackTraceElement {
       public String getFileName();
       public int getLineNumber();
       public String getClassName();
       public String getMethodName();
       public boolean isNativeMethod();
     }

     _How   to Design a Good API and Why it Matters
31
Overload With Care

     • Avoid ambiguous overloadings
             _ Multiple overloadings applicable to same actuals
             _ Conservative: no two with same number of args
     • Just because you can doesn't mean you should
             _ Often better to use a different name
     • If you must provide ambiguous overloadings,
            ensure same behavior for same arguments
     public TreeSet(Collection c); // Ignores order
     public TreeSet(SortedSet s); // Respects order



     _How   to Design a Good API and Why it Matters
32
Use Appropriate Parameter and Return Types


     • Favor interface types over classes for input
             _ Provides flexibility, performance
     • Use most specific possible input parameter type
             _ Moves error from runtime to compile time
     • Don't use string if a better type exists
             _ Strings are cumbersome, error-prone, and slow
     • Don't use floating point for monetary values
             _ Binary floating point causes inexact results!
     • Use double (64 bits) rather than float (32 bits)
             _ Precision loss is real, performance loss negligible




     _How   to Design a Good API and Why it Matters
33
Use Consistent Parameter Ordering
     Across Methods

     • Especially important if parameter types identical
       #include <string.h>
       char *strcpy (char *dest, char *src);
       void bcopy   (void *src, void *dst, int n);


       java.util.Collections – first parameter always
       collection to be modified or queried
       java.util.concurrent – time always specified as
       long delay, TimeUnit unit




     _How   to Design a Good API and Why it Matters
34
Avoid Long Parameter Lists

     • Three or fewer parameters is ideal
             _ More and users will have to refer to docs
     • Long lists of identically typed params harmful
             _ Programmers transpose parameters by mistake
             _ Programs still compile, run, but misbehave!
     • Two techniques for shortening parameter lists
             _ Break up method
             _ Create helper class to hold parameters
     // Eleven parameters including four consecutive ints
     HWND CreateWindow(LPCTSTR lpClassName, LPCTSTR lpWindowName,
           DWORD dwStyle, int x, int y, int nWidth, int nHeight,
           HWND hWndParent, HMENU hMenu, HINSTANCE hInstance,
           LPVOID lpParam);


     _How   to Design a Good API and Why it Matters
35
Avoid Return Values that Demand
     Exceptional Processing

     • return zero-length array or empty collection, not null

        package java.awt.image;
        public interface BufferedImageOp {
          // Returns the rendering hints for this operation,
          // or null if no hints have been set.
          public RenderingHints getRenderingHints();
        }




     _How   to Design a Good API and Why it Matters
36
V. Exception Design




     _How   to Design a Good API and Why it Matters
37
Throw Exceptions to Indicate
     Exceptional Conditions

     • Don’t force client to use exceptions for control flow
              private byte[] a = new byte[BUF_SIZE];
              void processBuffer (ByteBuffer buf) {
                try {
                  while (true) {
                    buf.get(a);
                    processBytes(tmp, BUF_SIZE);
                  }
                } catch (BufferUnderflowException e) {
                  int remaining = buf.remaining();
                  buf.get(a, 0, remaining);
                  processBytes(bufArray, remaining);
                }
              }
     • Conversely, don’t fail silently
               ThreadGroup.enumerate(Thread[] list)
     _How   to Design a Good API and Why it Matters
38
Favor Unchecked Exceptions

     • Checked – client must take recovery action
     • Unchecked – programming error
     • Overuse of checked exceptions causes boilerplate
     try {
         Foo f = (Foo) super.clone();
         ....
     } catch (CloneNotSupportedException e) {
         // This can't happen, since we’re Cloneable
         throw new AssertionError();
     }



     _How   to Design a Good API and Why it Matters
39
Include Failure-Capture Information in
     Exceptions

     • Allows diagnosis and repair or recovery
     • For unchecked exceptions, message suffices
     • For checked exceptions, provide accessors




     _How   to Design a Good API and Why it Matters
40
VI. Refactoring API Designs




     _How   to Design a Good API and Why it Matters
41
1. Sublist Operations in Vector

     public class Vector {
         public int indexOf(Object elem, int index);
         public int lastIndexOf(Object elem, int index);
         ...
     }


     • Not very powerful - supports only search
     • Hard too use without documentation




     _How   to Design a Good API and Why it Matters
42
Sublist Operations Refactored

     public interface List {
         List subList(int fromIndex, int toIndex);
         ...
     }


     • Extremely powerful - supports all operations
     • Use of interface reduces conceptual weight
             _ High power-to-weight ratio
     • Easy to use without documentation


     _How   to Design a Good API and Why it Matters
43
2. Thread-Local Variables

      // Broken - inappropriate use of String as capability.
       // Keys constitute a shared global namespace.
       public class ThreadLocal {
           private ThreadLocal() { } // Non-instantiable

                 // Sets current thread’s value for named variable.
                 public static void set(String key, Object value);

                 // Returns current thread’s value for named variable.
                 public static Object get(String key);
      }




     _How   to Design a Good API and Why it Matters
44
Thread-Local Variables Refactored (1)

      public class ThreadLocal {
           private ThreadLocal() { } // Noninstantiable

                public static class Key { Key() { } }
                // Generates a unique, unforgeable key
                public static Key getKey() { return new Key(); }
                public static void set(Key key, Object value);
                public static Object get(Key key);
      }


     • Works, but requires boilerplate code to use
      static ThreadLocal.Key serialNumberKey = ThreadLocal.getKey();
      ThreadLocal.set(serialNumberKey, nextSerialNumber());
      System.out.println(ThreadLocal.get(serialNumberKey));




     _How   to Design a Good API and Why it Matters
45
Thread-Local Variables Refactored (2)


      public class ThreadLocal {
          public ThreadLocal() { }
          public void set(Object value);
          public Object get();
      }


     • Removes clutter from API and client code
      static ThreadLocal serialNumber = new ThreadLocal();
      serialNumber.set(nextSerialNumber());
      System.out.println(serialNumber.get());




     _How   to Design a Good API and Why it Matters
46
Conclusion

     • API design is a noble and rewarding craft
             _ Improves the lot of programmers, end-users,
               companies
     • This talk covered some heuristics of the craft
             _ Don't adhere to them slavishly, but...
             _ Don't violate them without good reason
     • API design is tough
             _ Not a solitary activity
             _ Perfection is unachievable, but try anyway



     _How   to Design a Good API and Why it Matters
47
Shameless Self-Promotion




     _How   to Design a Good API and Why it Matters
48
How to Design a Good
     API and Why it Matters



       Joshua Bloch
       Principal Software Engineer

     _How   to Design a Good API and Why it Matters
49

More Related Content

What's hot

Reference Architecture-Validated & Tested Approach to Define Network Design
Reference Architecture-Validated & Tested Approach to Define Network DesignReference Architecture-Validated & Tested Approach to Define Network Design
Reference Architecture-Validated & Tested Approach to Define Network DesignDataWorks Summit
 
How to Execute a Successful API Strategy
How to Execute a Successful API StrategyHow to Execute a Successful API Strategy
How to Execute a Successful API StrategyMatt McLarty
 
C10k and beyond - Uri Shamay, Akamai
C10k and beyond - Uri Shamay, AkamaiC10k and beyond - Uri Shamay, Akamai
C10k and beyond - Uri Shamay, AkamaiCodemotion Tel Aviv
 
MOLOCH: Search for Full Packet Capture (OA Cyber Summit)
MOLOCH: Search for Full Packet Capture (OA Cyber Summit)MOLOCH: Search for Full Packet Capture (OA Cyber Summit)
MOLOCH: Search for Full Packet Capture (OA Cyber Summit)Open Analytics
 
PPT on Angular 2 Development Tutorial
PPT on Angular 2 Development TutorialPPT on Angular 2 Development Tutorial
PPT on Angular 2 Development TutorialPaddy Lock
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
RPC에서 REST까지 간단한 개념소개
RPC에서 REST까지 간단한 개념소개RPC에서 REST까지 간단한 개념소개
RPC에서 REST까지 간단한 개념소개Wonchang Song
 
NGINX Installation and Tuning
NGINX Installation and TuningNGINX Installation and Tuning
NGINX Installation and TuningNGINX, Inc.
 
Web API authentication and authorization
Web API authentication and authorization Web API authentication and authorization
Web API authentication and authorization Chalermpon Areepong
 
NGINX: High Performance Load Balancing
NGINX: High Performance Load BalancingNGINX: High Performance Load Balancing
NGINX: High Performance Load BalancingNGINX, Inc.
 
NGINX Kubernetes Ingress Controller: Getting Started – EMEA
NGINX Kubernetes Ingress Controller: Getting Started – EMEANGINX Kubernetes Ingress Controller: Getting Started – EMEA
NGINX Kubernetes Ingress Controller: Getting Started – EMEAAine Long
 

What's hot (20)

Reference Architecture-Validated & Tested Approach to Define Network Design
Reference Architecture-Validated & Tested Approach to Define Network DesignReference Architecture-Validated & Tested Approach to Define Network Design
Reference Architecture-Validated & Tested Approach to Define Network Design
 
StarlingX - A Platform for the Distributed Edge | Ildiko Vancsa
StarlingX - A Platform for the Distributed Edge | Ildiko VancsaStarlingX - A Platform for the Distributed Edge | Ildiko Vancsa
StarlingX - A Platform for the Distributed Edge | Ildiko Vancsa
 
How to Execute a Successful API Strategy
How to Execute a Successful API StrategyHow to Execute a Successful API Strategy
How to Execute a Successful API Strategy
 
gRPC in Go
gRPC in GogRPC in Go
gRPC in Go
 
NETCONF YANG tutorial
NETCONF YANG tutorialNETCONF YANG tutorial
NETCONF YANG tutorial
 
C10k and beyond - Uri Shamay, Akamai
C10k and beyond - Uri Shamay, AkamaiC10k and beyond - Uri Shamay, Akamai
C10k and beyond - Uri Shamay, Akamai
 
HAProxy 1.9
HAProxy 1.9HAProxy 1.9
HAProxy 1.9
 
MOLOCH: Search for Full Packet Capture (OA Cyber Summit)
MOLOCH: Search for Full Packet Capture (OA Cyber Summit)MOLOCH: Search for Full Packet Capture (OA Cyber Summit)
MOLOCH: Search for Full Packet Capture (OA Cyber Summit)
 
PPT on Angular 2 Development Tutorial
PPT on Angular 2 Development TutorialPPT on Angular 2 Development Tutorial
PPT on Angular 2 Development Tutorial
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
RPC에서 REST까지 간단한 개념소개
RPC에서 REST까지 간단한 개념소개RPC에서 REST까지 간단한 개념소개
RPC에서 REST까지 간단한 개념소개
 
Power-up services with gRPC
Power-up services with gRPCPower-up services with gRPC
Power-up services with gRPC
 
Restful web services ppt
Restful web services pptRestful web services ppt
Restful web services ppt
 
Netflow Protocol
Netflow ProtocolNetflow Protocol
Netflow Protocol
 
NGINX Installation and Tuning
NGINX Installation and TuningNGINX Installation and Tuning
NGINX Installation and Tuning
 
Hadoop Oozie
Hadoop OozieHadoop Oozie
Hadoop Oozie
 
Web API authentication and authorization
Web API authentication and authorization Web API authentication and authorization
Web API authentication and authorization
 
Api types
Api typesApi types
Api types
 
NGINX: High Performance Load Balancing
NGINX: High Performance Load BalancingNGINX: High Performance Load Balancing
NGINX: High Performance Load Balancing
 
NGINX Kubernetes Ingress Controller: Getting Started – EMEA
NGINX Kubernetes Ingress Controller: Getting Started – EMEANGINX Kubernetes Ingress Controller: Getting Started – EMEA
NGINX Kubernetes Ingress Controller: Getting Started – EMEA
 

Viewers also liked

Api anti patterns
Api anti patternsApi anti patterns
Api anti patternsMike Pearce
 
APIs: the Glue of Cloud Computing
APIs: the Glue of Cloud ComputingAPIs: the Glue of Cloud Computing
APIs: the Glue of Cloud Computing3scale
 
Golden Rules of API Design
Golden Rules of API DesignGolden Rules of API Design
Golden Rules of API DesignDavid Koelle
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsStormpath
 
Microsoft v Google UI Design Debate Presentation (2015)
Microsoft v Google UI Design Debate Presentation (2015)Microsoft v Google UI Design Debate Presentation (2015)
Microsoft v Google UI Design Debate Presentation (2015)Ben Freeman
 
Rdf with contexts
Rdf with contextsRdf with contexts
Rdf with contextsPat Hayes
 
Hourglass Interfaces for C++ APIs - CppCon 2014
Hourglass Interfaces for C++ APIs - CppCon 2014Hourglass Interfaces for C++ APIs - CppCon 2014
Hourglass Interfaces for C++ APIs - CppCon 2014Stefanus Du Toit
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion PrincipleTom Philip
 
Goals Of Software Design - The main goals
Goals Of Software Design - The main goalsGoals Of Software Design - The main goals
Goals Of Software Design - The main goalsparag
 
170215 tech tourgrowth502017
170215 tech tourgrowth502017170215 tech tourgrowth502017
170215 tech tourgrowth502017Gaudefroy Ariane
 
Google Search Engine
Google Search Engine Google Search Engine
Google Search Engine Aniket_1415
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Mario Cardinal
 
Some REST Design Patterns (and Anti-Patterns) - SOA Symposium 2009
Some REST Design Patterns (and Anti-Patterns) - SOA Symposium 2009Some REST Design Patterns (and Anti-Patterns) - SOA Symposium 2009
Some REST Design Patterns (and Anti-Patterns) - SOA Symposium 2009Cesare Pautasso
 
API 101 - Understanding APIs.
API 101 - Understanding APIs.API 101 - Understanding APIs.
API 101 - Understanding APIs.Kirsten Hunter
 
Designing better user interfaces
Designing better user interfacesDesigning better user interfaces
Designing better user interfacesJohan Ronsse
 
Questions product managers should ask customers
Questions product managers should ask customersQuestions product managers should ask customers
Questions product managers should ask customersProductPlan
 

Viewers also liked (20)

Api anti patterns
Api anti patternsApi anti patterns
Api anti patterns
 
APIs: the Glue of Cloud Computing
APIs: the Glue of Cloud ComputingAPIs: the Glue of Cloud Computing
APIs: the Glue of Cloud Computing
 
Golden Rules of API Design
Golden Rules of API DesignGolden Rules of API Design
Golden Rules of API Design
 
RESTful API Design, Second Edition
RESTful API Design, Second EditionRESTful API Design, Second Edition
RESTful API Design, Second Edition
 
API Design - 3rd Edition
API Design - 3rd EditionAPI Design - 3rd Edition
API Design - 3rd Edition
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIs
 
Microsoft v Google UI Design Debate Presentation (2015)
Microsoft v Google UI Design Debate Presentation (2015)Microsoft v Google UI Design Debate Presentation (2015)
Microsoft v Google UI Design Debate Presentation (2015)
 
Rdf with contexts
Rdf with contextsRdf with contexts
Rdf with contexts
 
Hourglass Interfaces for C++ APIs - CppCon 2014
Hourglass Interfaces for C++ APIs - CppCon 2014Hourglass Interfaces for C++ APIs - CppCon 2014
Hourglass Interfaces for C++ APIs - CppCon 2014
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion Principle
 
Goals Of Software Design - The main goals
Goals Of Software Design - The main goalsGoals Of Software Design - The main goals
Goals Of Software Design - The main goals
 
170215 tech tourgrowth502017
170215 tech tourgrowth502017170215 tech tourgrowth502017
170215 tech tourgrowth502017
 
Google Search Engine
Google Search Engine Google Search Engine
Google Search Engine
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.
 
Some REST Design Patterns (and Anti-Patterns) - SOA Symposium 2009
Some REST Design Patterns (and Anti-Patterns) - SOA Symposium 2009Some REST Design Patterns (and Anti-Patterns) - SOA Symposium 2009
Some REST Design Patterns (and Anti-Patterns) - SOA Symposium 2009
 
API 101 - Understanding APIs.
API 101 - Understanding APIs.API 101 - Understanding APIs.
API 101 - Understanding APIs.
 
Designing better user interfaces
Designing better user interfacesDesigning better user interfaces
Designing better user interfaces
 
APIs: The New Security Layer
APIs: The New Security LayerAPIs: The New Security Layer
APIs: The New Security Layer
 
Google Brand Analysis
Google Brand AnalysisGoogle Brand Analysis
Google Brand Analysis
 
Questions product managers should ask customers
Questions product managers should ask customersQuestions product managers should ask customers
Questions product managers should ask customers
 

Similar to How To Design A Good A P I And Why It Matters G O O G L E

How to design good api
How to design good apiHow to design good api
How to design good apiOsama Shakir
 
The Power Of Refactoring (PHPNW)
The Power Of Refactoring (PHPNW)The Power Of Refactoring (PHPNW)
The Power Of Refactoring (PHPNW)Stefan Koopmanschap
 
Sap web dynpro – practices for better functionality
Sap web dynpro – practices for better functionalitySap web dynpro – practices for better functionality
Sap web dynpro – practices for better functionalityanjalirao366
 
Dev Learn Handout - Session 604
Dev Learn Handout - Session 604Dev Learn Handout - Session 604
Dev Learn Handout - Session 604Chad Udell
 
MuleSoft Surat Meetup#39 - Pragmatic API Led Connectivity
MuleSoft Surat Meetup#39 - Pragmatic API Led ConnectivityMuleSoft Surat Meetup#39 - Pragmatic API Led Connectivity
MuleSoft Surat Meetup#39 - Pragmatic API Led ConnectivityJitendra Bafna
 
API Specifications and Best Practices | MuleSoft Mysore Meetup #4
API Specifications and Best Practices | MuleSoft Mysore Meetup #4API Specifications and Best Practices | MuleSoft Mysore Meetup #4
API Specifications and Best Practices | MuleSoft Mysore Meetup #4MysoreMuleSoftMeetup
 
Designing Good API & Its Importance
Designing Good API & Its ImportanceDesigning Good API & Its Importance
Designing Good API & Its ImportanceImran M Yousuf
 
Why your APIs should fly first class
Why your APIs should fly first classWhy your APIs should fly first class
Why your APIs should fly first classLibbySchulze
 
Trouble with Performance Debugging? Not Anymore with Choreo, the AI-Assisted ...
Trouble with Performance Debugging? Not Anymore with Choreo, the AI-Assisted ...Trouble with Performance Debugging? Not Anymore with Choreo, the AI-Assisted ...
Trouble with Performance Debugging? Not Anymore with Choreo, the AI-Assisted ...WSO2
 
Using Artificial Intelligence in Software Engineering
Using Artificial Intelligence in Software EngineeringUsing Artificial Intelligence in Software Engineering
Using Artificial Intelligence in Software EngineeringFaculty of Computer Science
 
Your API Sucks! Why developers hang up and how to stop that.
Your API Sucks! Why developers hang up and how to stop that.Your API Sucks! Why developers hang up and how to stop that.
Your API Sucks! Why developers hang up and how to stop that.Apigee | Google Cloud
 
The Power Of Refactoring (4developers Krakow)
The Power Of Refactoring (4developers Krakow)The Power Of Refactoring (4developers Krakow)
The Power Of Refactoring (4developers Krakow)Stefan Koopmanschap
 
End to End Testing: Bug Squashing for API Developers
End to End Testing: Bug Squashing for API Developers End to End Testing: Bug Squashing for API Developers
End to End Testing: Bug Squashing for API Developers Apigee | Google Cloud
 
Faridabad MuleSoft Meetup Group (1).pdf
Faridabad MuleSoft Meetup Group (1).pdfFaridabad MuleSoft Meetup Group (1).pdf
Faridabad MuleSoft Meetup Group (1).pdfRohitSingh585124
 
[WSO2 API Day Chicago 2019] Sustainable Competitive Advantage
[WSO2 API Day Chicago 2019] Sustainable Competitive Advantage [WSO2 API Day Chicago 2019] Sustainable Competitive Advantage
[WSO2 API Day Chicago 2019] Sustainable Competitive Advantage WSO2
 

Similar to How To Design A Good A P I And Why It Matters G O O G L E (20)

Keynoteof A P I
Keynoteof A P IKeynoteof A P I
Keynoteof A P I
 
How to design good api
How to design good apiHow to design good api
How to design good api
 
The Power Of Refactoring (PHPNW)
The Power Of Refactoring (PHPNW)The Power Of Refactoring (PHPNW)
The Power Of Refactoring (PHPNW)
 
How to define an api
How to define an apiHow to define an api
How to define an api
 
Sap web dynpro – practices for better functionality
Sap web dynpro – practices for better functionalitySap web dynpro – practices for better functionality
Sap web dynpro – practices for better functionality
 
Dev Learn Handout - Session 604
Dev Learn Handout - Session 604Dev Learn Handout - Session 604
Dev Learn Handout - Session 604
 
MuleSoft Surat Meetup#39 - Pragmatic API Led Connectivity
MuleSoft Surat Meetup#39 - Pragmatic API Led ConnectivityMuleSoft Surat Meetup#39 - Pragmatic API Led Connectivity
MuleSoft Surat Meetup#39 - Pragmatic API Led Connectivity
 
The Power of Refactoring
The Power of RefactoringThe Power of Refactoring
The Power of Refactoring
 
API Specifications and Best Practices | MuleSoft Mysore Meetup #4
API Specifications and Best Practices | MuleSoft Mysore Meetup #4API Specifications and Best Practices | MuleSoft Mysore Meetup #4
API Specifications and Best Practices | MuleSoft Mysore Meetup #4
 
Designing Good API & Its Importance
Designing Good API & Its ImportanceDesigning Good API & Its Importance
Designing Good API & Its Importance
 
API presentation
API presentationAPI presentation
API presentation
 
Why your APIs should fly first class
Why your APIs should fly first classWhy your APIs should fly first class
Why your APIs should fly first class
 
Trouble with Performance Debugging? Not Anymore with Choreo, the AI-Assisted ...
Trouble with Performance Debugging? Not Anymore with Choreo, the AI-Assisted ...Trouble with Performance Debugging? Not Anymore with Choreo, the AI-Assisted ...
Trouble with Performance Debugging? Not Anymore with Choreo, the AI-Assisted ...
 
Using Artificial Intelligence in Software Engineering
Using Artificial Intelligence in Software EngineeringUsing Artificial Intelligence in Software Engineering
Using Artificial Intelligence in Software Engineering
 
Effective API Design
Effective API DesignEffective API Design
Effective API Design
 
Your API Sucks! Why developers hang up and how to stop that.
Your API Sucks! Why developers hang up and how to stop that.Your API Sucks! Why developers hang up and how to stop that.
Your API Sucks! Why developers hang up and how to stop that.
 
The Power Of Refactoring (4developers Krakow)
The Power Of Refactoring (4developers Krakow)The Power Of Refactoring (4developers Krakow)
The Power Of Refactoring (4developers Krakow)
 
End to End Testing: Bug Squashing for API Developers
End to End Testing: Bug Squashing for API Developers End to End Testing: Bug Squashing for API Developers
End to End Testing: Bug Squashing for API Developers
 
Faridabad MuleSoft Meetup Group (1).pdf
Faridabad MuleSoft Meetup Group (1).pdfFaridabad MuleSoft Meetup Group (1).pdf
Faridabad MuleSoft Meetup Group (1).pdf
 
[WSO2 API Day Chicago 2019] Sustainable Competitive Advantage
[WSO2 API Day Chicago 2019] Sustainable Competitive Advantage [WSO2 API Day Chicago 2019] Sustainable Competitive Advantage
[WSO2 API Day Chicago 2019] Sustainable Competitive Advantage
 

Recently uploaded

ACCOUNTING FOR BUSINESS.II BRANCH ACCOUNTS NOTES
ACCOUNTING FOR BUSINESS.II BRANCH ACCOUNTS NOTESACCOUNTING FOR BUSINESS.II BRANCH ACCOUNTS NOTES
ACCOUNTING FOR BUSINESS.II BRANCH ACCOUNTS NOTESKumarJayaraman3
 
The Power Laws of Bitcoin: How can an S-curve be a power law?
The Power Laws of Bitcoin: How can an S-curve be a power law?The Power Laws of Bitcoin: How can an S-curve be a power law?
The Power Laws of Bitcoin: How can an S-curve be a power law?Stephen Perrenod
 
Remembering my Totem _Unity is Strength_ growing in Bophuthatswana_Matthews B...
Remembering my Totem _Unity is Strength_ growing in Bophuthatswana_Matthews B...Remembering my Totem _Unity is Strength_ growing in Bophuthatswana_Matthews B...
Remembering my Totem _Unity is Strength_ growing in Bophuthatswana_Matthews B...Matthews Bantsijang
 
Buy and Sell Urban Tots unlisted shares.pptx
Buy and Sell Urban Tots unlisted shares.pptxBuy and Sell Urban Tots unlisted shares.pptx
Buy and Sell Urban Tots unlisted shares.pptxPrecize Formely Leadoff
 
Stock Market Brief Deck for March 26.pdf
Stock Market Brief Deck for March 26.pdfStock Market Brief Deck for March 26.pdf
Stock Market Brief Deck for March 26.pdfMichael Silva
 
2024.03 Strategic Resources Presentation
2024.03 Strategic Resources Presentation2024.03 Strategic Resources Presentation
2024.03 Strategic Resources PresentationAdnet Communications
 
The unequal battle of inflation and the appropriate sustainable solution | Eu...
The unequal battle of inflation and the appropriate sustainable solution | Eu...The unequal battle of inflation and the appropriate sustainable solution | Eu...
The unequal battle of inflation and the appropriate sustainable solution | Eu...Antonis Zairis
 
What Key Factors Should Risk Officers Consider When Using Generative AI
What Key Factors Should Risk Officers Consider When Using Generative AIWhat Key Factors Should Risk Officers Consider When Using Generative AI
What Key Factors Should Risk Officers Consider When Using Generative AI360factors
 
India Economic Survey Complete for the year of 2022 to 2023
India Economic Survey Complete for the year of 2022 to 2023India Economic Survey Complete for the year of 2022 to 2023
India Economic Survey Complete for the year of 2022 to 2023SkillCircle
 
Contracts with Interdependent Preferences
Contracts with Interdependent PreferencesContracts with Interdependent Preferences
Contracts with Interdependent PreferencesGRAPE
 
Taipei, A Hidden Jewel in East Asia - PR Strategy for Tourism
Taipei, A Hidden Jewel in East Asia - PR Strategy for TourismTaipei, A Hidden Jewel in East Asia - PR Strategy for Tourism
Taipei, A Hidden Jewel in East Asia - PR Strategy for TourismBrian Lin
 
Lundin Gold March 2024 Corporate Presentation - PDAC v1.pdf
Lundin Gold March 2024 Corporate Presentation - PDAC v1.pdfLundin Gold March 2024 Corporate Presentation - PDAC v1.pdf
Lundin Gold March 2024 Corporate Presentation - PDAC v1.pdfAdnet Communications
 
ACCOUNTING FOR BUSINESS.II DEPARTMENTAL ACCOUNTS.
ACCOUNTING FOR BUSINESS.II DEPARTMENTAL ACCOUNTS.ACCOUNTING FOR BUSINESS.II DEPARTMENTAL ACCOUNTS.
ACCOUNTING FOR BUSINESS.II DEPARTMENTAL ACCOUNTS.KumarJayaraman3
 
LIC PRIVATISATION its a bane or boon.pptx
LIC PRIVATISATION its a bane or boon.pptxLIC PRIVATISATION its a bane or boon.pptx
LIC PRIVATISATION its a bane or boon.pptxsonamyadav7097
 
20240314 Calibre March 2024 Investor Presentation (FINAL).pdf
20240314 Calibre March 2024 Investor Presentation (FINAL).pdf20240314 Calibre March 2024 Investor Presentation (FINAL).pdf
20240314 Calibre March 2024 Investor Presentation (FINAL).pdfAdnet Communications
 
Sarlat Advisory - Corporate Brochure - 2024
Sarlat Advisory - Corporate Brochure - 2024Sarlat Advisory - Corporate Brochure - 2024
Sarlat Advisory - Corporate Brochure - 2024Guillaume Ⓥ Sarlat
 
Introduction to Entrepreneurship and Characteristics of an Entrepreneur
Introduction to Entrepreneurship and Characteristics of an EntrepreneurIntroduction to Entrepreneurship and Characteristics of an Entrepreneur
Introduction to Entrepreneurship and Characteristics of an Entrepreneurabcisahunter
 
Monthly Market Risk Update: March 2024 [SlideShare]
Monthly Market Risk Update: March 2024 [SlideShare]Monthly Market Risk Update: March 2024 [SlideShare]
Monthly Market Risk Update: March 2024 [SlideShare]Commonwealth
 
RWA Report 2024: Rise of Real-World Assets in Crypto | CoinGecko
RWA Report 2024: Rise of Real-World Assets in Crypto | CoinGeckoRWA Report 2024: Rise of Real-World Assets in Crypto | CoinGecko
RWA Report 2024: Rise of Real-World Assets in Crypto | CoinGeckoCoinGecko
 

Recently uploaded (20)

ACCOUNTING FOR BUSINESS.II BRANCH ACCOUNTS NOTES
ACCOUNTING FOR BUSINESS.II BRANCH ACCOUNTS NOTESACCOUNTING FOR BUSINESS.II BRANCH ACCOUNTS NOTES
ACCOUNTING FOR BUSINESS.II BRANCH ACCOUNTS NOTES
 
The Power Laws of Bitcoin: How can an S-curve be a power law?
The Power Laws of Bitcoin: How can an S-curve be a power law?The Power Laws of Bitcoin: How can an S-curve be a power law?
The Power Laws of Bitcoin: How can an S-curve be a power law?
 
Remembering my Totem _Unity is Strength_ growing in Bophuthatswana_Matthews B...
Remembering my Totem _Unity is Strength_ growing in Bophuthatswana_Matthews B...Remembering my Totem _Unity is Strength_ growing in Bophuthatswana_Matthews B...
Remembering my Totem _Unity is Strength_ growing in Bophuthatswana_Matthews B...
 
Buy and Sell Urban Tots unlisted shares.pptx
Buy and Sell Urban Tots unlisted shares.pptxBuy and Sell Urban Tots unlisted shares.pptx
Buy and Sell Urban Tots unlisted shares.pptx
 
Stock Market Brief Deck for March 26.pdf
Stock Market Brief Deck for March 26.pdfStock Market Brief Deck for March 26.pdf
Stock Market Brief Deck for March 26.pdf
 
2024.03 Strategic Resources Presentation
2024.03 Strategic Resources Presentation2024.03 Strategic Resources Presentation
2024.03 Strategic Resources Presentation
 
The unequal battle of inflation and the appropriate sustainable solution | Eu...
The unequal battle of inflation and the appropriate sustainable solution | Eu...The unequal battle of inflation and the appropriate sustainable solution | Eu...
The unequal battle of inflation and the appropriate sustainable solution | Eu...
 
What Key Factors Should Risk Officers Consider When Using Generative AI
What Key Factors Should Risk Officers Consider When Using Generative AIWhat Key Factors Should Risk Officers Consider When Using Generative AI
What Key Factors Should Risk Officers Consider When Using Generative AI
 
Commercial Bank Economic Capsule - March 2024
Commercial Bank Economic Capsule - March 2024Commercial Bank Economic Capsule - March 2024
Commercial Bank Economic Capsule - March 2024
 
India Economic Survey Complete for the year of 2022 to 2023
India Economic Survey Complete for the year of 2022 to 2023India Economic Survey Complete for the year of 2022 to 2023
India Economic Survey Complete for the year of 2022 to 2023
 
Contracts with Interdependent Preferences
Contracts with Interdependent PreferencesContracts with Interdependent Preferences
Contracts with Interdependent Preferences
 
Taipei, A Hidden Jewel in East Asia - PR Strategy for Tourism
Taipei, A Hidden Jewel in East Asia - PR Strategy for TourismTaipei, A Hidden Jewel in East Asia - PR Strategy for Tourism
Taipei, A Hidden Jewel in East Asia - PR Strategy for Tourism
 
Lundin Gold March 2024 Corporate Presentation - PDAC v1.pdf
Lundin Gold March 2024 Corporate Presentation - PDAC v1.pdfLundin Gold March 2024 Corporate Presentation - PDAC v1.pdf
Lundin Gold March 2024 Corporate Presentation - PDAC v1.pdf
 
ACCOUNTING FOR BUSINESS.II DEPARTMENTAL ACCOUNTS.
ACCOUNTING FOR BUSINESS.II DEPARTMENTAL ACCOUNTS.ACCOUNTING FOR BUSINESS.II DEPARTMENTAL ACCOUNTS.
ACCOUNTING FOR BUSINESS.II DEPARTMENTAL ACCOUNTS.
 
LIC PRIVATISATION its a bane or boon.pptx
LIC PRIVATISATION its a bane or boon.pptxLIC PRIVATISATION its a bane or boon.pptx
LIC PRIVATISATION its a bane or boon.pptx
 
20240314 Calibre March 2024 Investor Presentation (FINAL).pdf
20240314 Calibre March 2024 Investor Presentation (FINAL).pdf20240314 Calibre March 2024 Investor Presentation (FINAL).pdf
20240314 Calibre March 2024 Investor Presentation (FINAL).pdf
 
Sarlat Advisory - Corporate Brochure - 2024
Sarlat Advisory - Corporate Brochure - 2024Sarlat Advisory - Corporate Brochure - 2024
Sarlat Advisory - Corporate Brochure - 2024
 
Introduction to Entrepreneurship and Characteristics of an Entrepreneur
Introduction to Entrepreneurship and Characteristics of an EntrepreneurIntroduction to Entrepreneurship and Characteristics of an Entrepreneur
Introduction to Entrepreneurship and Characteristics of an Entrepreneur
 
Monthly Market Risk Update: March 2024 [SlideShare]
Monthly Market Risk Update: March 2024 [SlideShare]Monthly Market Risk Update: March 2024 [SlideShare]
Monthly Market Risk Update: March 2024 [SlideShare]
 
RWA Report 2024: Rise of Real-World Assets in Crypto | CoinGecko
RWA Report 2024: Rise of Real-World Assets in Crypto | CoinGeckoRWA Report 2024: Rise of Real-World Assets in Crypto | CoinGecko
RWA Report 2024: Rise of Real-World Assets in Crypto | CoinGecko
 

How To Design A Good A P I And Why It Matters G O O G L E

  • 1. How to Design a Good API and Why it Matters Joshua Bloch Principal Software Engineer _How to Design a Good API and Why it Matters 1
  • 2. Why is API Design Important? • APIs can be among a company's greatest assets _ Customers invest heavily: buying, writing, learning _ Cost to stop using an API can be prohibitive _ Successful public APIs capture customers • Can also be among company's greatest liabilities _ Bad APIs result in unending stream of support calls • Public APIs are forever - one chance to get it right _How to Design a Good API and Why it Matters 2
  • 3. Why is API Design Important to You? • If you program, you are an API designer _ Good code is modular–each module has an API • Useful modules tend to get reused _ Once module has users, can’t change API at will _ Good reusable modules are corporate assets • Thinking in terms of APIs improves code quality _How to Design a Good API and Why it Matters 3
  • 4. Characteristics of a Good API • Easy to learn • Easy to use, even without documentation • Hard to misuse • Easy to read and maintain code that uses it • Sufficiently powerful to satisfy requirements • Easy to extend • Appropriate to audience _How to Design a Good API and Why it Matters 4
  • 5. Outline I. The Process of API Design II. General Principles III. Class Design IV. Method Design V. Exception Design VI. Refactoring API Designs _How to Design a Good API and Why it Matters 5
  • 6. I. The Process of API Design _How to Design a Good API and Why it Matters 6
  • 7. Gather Requirements–with a Healthy Degree of Skepticism • Often you'll get proposed solutions instead _ Better solutions may exist • Your job is to extract true requirements _ Should take the form of use-cases • Can be easier and more rewarding to build something more general Good _How to Design a Good API and Why it Matters 7
  • 8. Start with Short Spec–1 Page is Ideal • At this stage, agility trumps completeness • Bounce spec off as many people as possible _ Listen to their input and take it seriously • If you keep the spec short, it’s easy to modify • Flesh it out as you gain confidence _ This necessarily involves coding _How to Design a Good API and Why it Matters 8
  • 9. Write to Your API Early and Often • Start before you've implemented the API _ Saves you doing implementation you'll throw away • Start before you've even specified it properly _ Saves you from writing specs you'll throw away • Continue writing to API as you flesh it out _ Prevents nasty surprises _ Code lives on as examples, unit tests _How to Design a Good API and Why it Matters 9
  • 10. Writing to SPI is Even More Important • Service Provider Interface (SPI) _ Plug-in interface enabling multiple implementations _ Example: Java Cryptography Extension (JCE) • Write multiple plug-ins before release _ If you write one, it probably won't support another _ If you write two, it will support more with difficulty _ If you write three, it will work fine • Will Tracz calls this “The Rule of Threes” (Confessions of a Used Program Salesman, Addison-Wesley, 1995) Bad _How to Design a Good API and Why it Matters 10
  • 11. Maintain Realistic Expectations • Most API designs are over-constrained _ You won't be able to please everyone _ Aim to displease everyone equally • Expect to make mistakes _ A few years of real-world use will flush them out _ Expect to evolve API _How to Design a Good API and Why it Matters 11
  • 12. II. General Principles _How to Design a Good API and Why it Matters 12
  • 13. API Should Do One Thing and Do it Well • Functionality should be easy to explain _ If it's hard to name, that's generally a bad sign _ Good names drive development _ Be amenable to splitting and merging modules _How to Design a Good API and Why it Matters 13
  • 14. API Should Be As Small As Possible But No Smaller • API should satisfy its requirements • When in doubt leave it out _ Functionality, classes, methods, parameters, etc. _ You can always add, but you can never remove • Conceptual weight more important than bulk • Look for a good power-to-weight ratio _How to Design a Good API and Why it Matters 14
  • 15. Implementation Should Not Impact API • Implementation details _ Confuse users _ Inhibit freedom to change implementation • Be aware of what is an implementation detail _ Do not overspecify the behavior of methods _ For example: do not specify hash functions _ All tuning parameters are suspect • Don't let implementation details “leak” into API _ On-disk and on-the-wire formats, exceptions _How to Design a Good API and Why it Matters 15
  • 16. Minimize Accessibility of Everything • Make classes and members as private as possible • Public classes should have no public fields (with the exception of constants) • This maximizes information hiding • Allows modules to be used, understood, built, tested, and debugged independently _How to Design a Good API and Why it Matters 16
  • 17. Names Matter–API is a Little Language • Names Should Be Largely Self-Explanatory _ Avoid cryptic abbreviations • Be consistent–same word means same thing _ Throughout API, (Across APIs on the platform) • Be regular–strive for symmetry • Code should read like prose if (car.speed() > 2 * SPEED_LIMIT) generateAlert(quot;Watch out for cops!quot;); _How to Design a Good API and Why it Matters 17
  • 18. Documentation Matters Reuse is something that is far easier to say than to do. Doing it requires both good design and very good documentation. Even when we see good design, which is still infrequently, we won't see the components reused without good documentation. - D. L. Parnas, _Software Aging. Proceedings of 16th International Conference Software Engineering, 1994 _How to Design a Good API and Why it Matters 18
  • 19. Document Religiously • Document every class, interface, method, constructor, parameter, and exception _ Class: what an instance represents _ Method: contract between method and its client _ Preconditions, postconditions, side-effects _ Parameter: indicate units, form, ownership • Document state space very carefully _How to Design a Good API and Why it Matters 19
  • 20. Consider Performance Consequences of API Design Decisions • Bad decisions can limit performance _ Making type mutable _ Providing constructor instead of static factory _ Using implementation type instead of interface • Do not warp API to gain performance _ Underlying performance issue will get fixed, but headaches will be with you forever _ Good design usually coincides with good performance _How to Design a Good API and Why it Matters 20
  • 21. Effects of API Design Decisions on Performance are Real and Permanent • Component.getSize() returns Dimension • Dimension is mutable • Each getSize call must allocate Dimension • Causes millions of needless object allocations • Alternative added in 1.2; old client code still slow _How to Design a Good API and Why it Matters 21
  • 22. API Must Coexist Peacefully with Platform • Do what is customary _ Obey standard naming conventions _ Avoid obsolete parameter and return types _ Mimic patterns in core APIs and language • Take advantage of API-friendly features _ Generics, varargs, enums, default arguments • Know and avoid API traps and pitfalls _ Finalizers, public static final arrays _How to Design a Good API and Why it Matters 22
  • 23. III. Class Design _How to Design a Good API and Why it Matters 23
  • 24. Minimize Mutability • Classes should be immutable unless there’s a good reason to do otherwise _ Advantages: simple, thread-safe, reusable _ Disadvantage: separate object for each value • If mutable, keep state-space small, well-defined _ Make clear when it's legal to call which method Bad: Date, Calendar Good: TimerTask _How to Design a Good API and Why it Matters 24
  • 25. Subclass Only Where It Makes Sense • Subclassing implies substitutability (Liskov) _ Subclass only when is-a relationship exists _ Otherwise, use composition • Public classes should not subclass other public classes for ease of implementation Bad: Properties extends Hashtable Stack extends Vector Good: Set extends Collection _How to Design a Good API and Why it Matters 25
  • 26. Design and Document for Inheritance or Else Prohibit it • Inheritance violates encapsulation (Snyder, ‘86) _ Subclass sensitive to implementation details of superclass • If you allow subclassing, document self-use _ How do methods use one another? • Conservative policy: all concrete classes final Bad: Many concrete classes in J2SE libraries Good: AbstractSet, AbstractMap _How to Design a Good API and Why it Matters 26
  • 27. IV. Method Design _How to Design a Good API and Why it Matters 27
  • 28. Don't Make the Client Do Anything the Module Could Do • Reduce need for boilerplate code _ Generally done via cut-and-paste _ Ugly, annoying, and error-prone import org.w3c.dom.*; import java.io.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; // DOM code to write an XML document to a specified output stream. private static final void writeDoc(Document doc, OutputStream out)throws IOException{ try { Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId()); t.transform(new DOMSource(doc), new StreamResult(out)); } catch(TransformerException e) { throw new AssertionError(e); // Can’t happen! } } _How to Design a Good API and Why it Matters 28
  • 29. Don't Violate the Principle of Least Astonishment • User of API should not be surprised by behavior _ It's worth extra implementation effort _ It's even worth reduced performance public class Thread implements Runnable { // Tests whether current thread has been interrupted. // Clears the interrupted status of current thread. public static boolean interrupted(); } _How to Design a Good API and Why it Matters 29
  • 30. Fail Fast–Report Errors as Soon as Possible After They Occur • Compile time is best - static typing, generics • At runtime, first bad method invocation is best _ Method should be failure-atomic // A Properties instance maps strings to strings public class Properties extends Hashtable { public Object put(Object key, Object value); // Throws ClassCastException if this properties // contains any keys or values that are not strings public void save(OutputStream out, String comments); } _How to Design a Good API and Why it Matters 30
  • 31. Provide Programmatic Access to All Data Available in String Form • Otherwise, clients will parse strings _ Painful for clients _ Worse, turns string format into de facto API public class Throwable { public void printStackTrace(PrintStream s); public StackTraceElement[] getStackTrace(); // Since 1.4 } public final class StackTraceElement { public String getFileName(); public int getLineNumber(); public String getClassName(); public String getMethodName(); public boolean isNativeMethod(); } _How to Design a Good API and Why it Matters 31
  • 32. Overload With Care • Avoid ambiguous overloadings _ Multiple overloadings applicable to same actuals _ Conservative: no two with same number of args • Just because you can doesn't mean you should _ Often better to use a different name • If you must provide ambiguous overloadings, ensure same behavior for same arguments public TreeSet(Collection c); // Ignores order public TreeSet(SortedSet s); // Respects order _How to Design a Good API and Why it Matters 32
  • 33. Use Appropriate Parameter and Return Types • Favor interface types over classes for input _ Provides flexibility, performance • Use most specific possible input parameter type _ Moves error from runtime to compile time • Don't use string if a better type exists _ Strings are cumbersome, error-prone, and slow • Don't use floating point for monetary values _ Binary floating point causes inexact results! • Use double (64 bits) rather than float (32 bits) _ Precision loss is real, performance loss negligible _How to Design a Good API and Why it Matters 33
  • 34. Use Consistent Parameter Ordering Across Methods • Especially important if parameter types identical #include <string.h> char *strcpy (char *dest, char *src); void bcopy (void *src, void *dst, int n); java.util.Collections – first parameter always collection to be modified or queried java.util.concurrent – time always specified as long delay, TimeUnit unit _How to Design a Good API and Why it Matters 34
  • 35. Avoid Long Parameter Lists • Three or fewer parameters is ideal _ More and users will have to refer to docs • Long lists of identically typed params harmful _ Programmers transpose parameters by mistake _ Programs still compile, run, but misbehave! • Two techniques for shortening parameter lists _ Break up method _ Create helper class to hold parameters // Eleven parameters including four consecutive ints HWND CreateWindow(LPCTSTR lpClassName, LPCTSTR lpWindowName, DWORD dwStyle, int x, int y, int nWidth, int nHeight, HWND hWndParent, HMENU hMenu, HINSTANCE hInstance, LPVOID lpParam); _How to Design a Good API and Why it Matters 35
  • 36. Avoid Return Values that Demand Exceptional Processing • return zero-length array or empty collection, not null package java.awt.image; public interface BufferedImageOp { // Returns the rendering hints for this operation, // or null if no hints have been set. public RenderingHints getRenderingHints(); } _How to Design a Good API and Why it Matters 36
  • 37. V. Exception Design _How to Design a Good API and Why it Matters 37
  • 38. Throw Exceptions to Indicate Exceptional Conditions • Don’t force client to use exceptions for control flow private byte[] a = new byte[BUF_SIZE]; void processBuffer (ByteBuffer buf) { try { while (true) { buf.get(a); processBytes(tmp, BUF_SIZE); } } catch (BufferUnderflowException e) { int remaining = buf.remaining(); buf.get(a, 0, remaining); processBytes(bufArray, remaining); } } • Conversely, don’t fail silently ThreadGroup.enumerate(Thread[] list) _How to Design a Good API and Why it Matters 38
  • 39. Favor Unchecked Exceptions • Checked – client must take recovery action • Unchecked – programming error • Overuse of checked exceptions causes boilerplate try { Foo f = (Foo) super.clone(); .... } catch (CloneNotSupportedException e) { // This can't happen, since we’re Cloneable throw new AssertionError(); } _How to Design a Good API and Why it Matters 39
  • 40. Include Failure-Capture Information in Exceptions • Allows diagnosis and repair or recovery • For unchecked exceptions, message suffices • For checked exceptions, provide accessors _How to Design a Good API and Why it Matters 40
  • 41. VI. Refactoring API Designs _How to Design a Good API and Why it Matters 41
  • 42. 1. Sublist Operations in Vector public class Vector { public int indexOf(Object elem, int index); public int lastIndexOf(Object elem, int index); ... } • Not very powerful - supports only search • Hard too use without documentation _How to Design a Good API and Why it Matters 42
  • 43. Sublist Operations Refactored public interface List { List subList(int fromIndex, int toIndex); ... } • Extremely powerful - supports all operations • Use of interface reduces conceptual weight _ High power-to-weight ratio • Easy to use without documentation _How to Design a Good API and Why it Matters 43
  • 44. 2. Thread-Local Variables // Broken - inappropriate use of String as capability. // Keys constitute a shared global namespace. public class ThreadLocal { private ThreadLocal() { } // Non-instantiable // Sets current thread’s value for named variable. public static void set(String key, Object value); // Returns current thread’s value for named variable. public static Object get(String key); } _How to Design a Good API and Why it Matters 44
  • 45. Thread-Local Variables Refactored (1) public class ThreadLocal { private ThreadLocal() { } // Noninstantiable public static class Key { Key() { } } // Generates a unique, unforgeable key public static Key getKey() { return new Key(); } public static void set(Key key, Object value); public static Object get(Key key); } • Works, but requires boilerplate code to use static ThreadLocal.Key serialNumberKey = ThreadLocal.getKey(); ThreadLocal.set(serialNumberKey, nextSerialNumber()); System.out.println(ThreadLocal.get(serialNumberKey)); _How to Design a Good API and Why it Matters 45
  • 46. Thread-Local Variables Refactored (2) public class ThreadLocal { public ThreadLocal() { } public void set(Object value); public Object get(); } • Removes clutter from API and client code static ThreadLocal serialNumber = new ThreadLocal(); serialNumber.set(nextSerialNumber()); System.out.println(serialNumber.get()); _How to Design a Good API and Why it Matters 46
  • 47. Conclusion • API design is a noble and rewarding craft _ Improves the lot of programmers, end-users, companies • This talk covered some heuristics of the craft _ Don't adhere to them slavishly, but... _ Don't violate them without good reason • API design is tough _ Not a solitary activity _ Perfection is unachievable, but try anyway _How to Design a Good API and Why it Matters 47
  • 48. Shameless Self-Promotion _How to Design a Good API and Why it Matters 48
  • 49. How to Design a Good API and Why it Matters Joshua Bloch Principal Software Engineer _How to Design a Good API and Why it Matters 49