SlideShare a Scribd company logo
1 of 37
API Design




Ferenc Mihaly
Senior Software Architect



November 9, 2011



                                                                             Slide 1
                            Copyright © Open Text Corporation. All rights reserved.
Agenda

 Introduction: Why it matters?
 Consider the perspective of the caller
 Keep it simple
 Strive for consistency
 Choose memorable names
 Specify the behaviour
 Make it safe
 Anticipate evolution
 Write helpful documentation




                                           Slide 2
Agenda

 Introduction: Why it matters?
 Consider the perspective of the caller
 Keep it simple
 Strive for consistency
 Choose memorable names
 Specify the behaviour
 Make it safe
 Anticipate evolution
 Write helpful documentation




                                           Slide 3
Why it matters?




      “Software artifacts that
      cannot attract programmers
      are not reused, and fade
      into oblivion.”
                      Brian Foote

                                     Slide 4
Why it matters?




      “The impact of API design
      choices on users sometimes
      shows time penalties of a
      factor of 3 to 10.”
                      Brad Myers

                                    Slide 5
Why it matters?




      “Public APIs, like
      diamonds, are forever. You
      have one chance to get it
      right so give it your best .”
                         Joshua Bloch

                                         Slide 6
Why it matters?




      “A key lesson here is that API
      is not just a documented class.
      And, APIs don't just happen;
      they are a big investment..”
                       Erich Gamma

                                        Slide 7
Agenda

 Introduction: Why it matters?
 Consider the perspective of the caller
 Keep it simple
 Strive for consistency
 Choose memorable names
 Specify the behaviour
 Make it safe
 Anticipate evolution
 Write helpful documentation




                                           Slide 8
Consider the perspective of the caller

                          Implementation focus results in poor APIs:

                           class ContentInstance
                           java.lang.Object
                              extended by DataObject
                                 extended by ManagedObject
                                    extended by ExtensibleObject
                                       extended by ContentItem
                                          extended by ContentInstance


                           All Implemented Interfaces:
                           IAttributedObject, IChannelAssociate, IPersistable,
                             IRelatedAttribute, java.io.Serializable




                                                                           Slide 9
Consider the perspective of the caller

                           Implementation perspective
                            class Document {
                                String getTag();
                                boolean isTagged(String tag);
                                void remove(String tag);
                                void removeTag(String tag);
                            }




                           Caller perspective
                          if(document.getTag().equals(“Best Practices”))


                          if(document.isTagged(“Best Practices”))


                          document.remove(“Best Practices”)


                          document.removeTag(“Best Practices”)


                                                                           Slide 10
Consider the perspective of the caller

                          Write client code first
                          Write client code for all major use cases
                          Ask yourself
                            Is this code simple?
                            Is this code intuitive?
                            Is this code consistent?
                            Is this code performant?
                            Does this code reveal any implementation
                             details?

                          Not a wasted effort
                            Code samples reused in tests
                            Code samples reused in documentation



                                                                       Slide 11
Agenda

 Introduction: Why it matters?
 Consider the perspective of the caller
 Keep it simple
 Strive for consistency
 Choose memorable names
 Specify the behaviour
 Make it safe
 Anticipate evolution
 Write helpful documentation




                                           Slide 12
Keep it simple




      “Simplicity is the ultimate
      sophistication”

                       Leonardo da Vinci

                                            Slide 13
Keep it Simple

 Measuring Conceptual Complexity
  try {
      AuthenticationProvider20 provider = new LocalAuthenticationProvider19();
      SearchCriteria18 criteria = new SearchCriteria17(EntityName16.USER15);
      criteria.addPropertyToFetch14(PropertyName13.COMMON_NAME12);
      criteria.addPropertyToFetch(PropertyName.PHONE11);
      criteria.addPropertyToMatch10(PropertyName.DEPARTMENT9, "R&D");
      criteria.addPropertyToMatch(PropertyName.LOCATION8, "Waterloo");
      criteria.setSortProperty7(PropertyName.COMMON_NAME);
      ProfileIterator6 iterator = provider.search5(criteria);
      while(iterator.hasNext()4){
          Profile3 profile = iterator.next()2;
          Property1 commonName = profile.getProperty0(PropertyName.COMMON_NAME);
          Property phone = profile.getProperty(PropertyName.PHONE);
          System.out.println(commonName.getValue()-1, “ ”, phone.getValue());
      }
  }
  catch(AuthenticationProviderException-2 e) {
  }

 The higher score is better; less than zero means too complex!
                                                                                   Slide 14
Keep it simple

                  Accidental complexity
                    Avoid asking callers to extend classes
                    Avoid asking callers to implement interfaces
                    Avoid “Gang of Four” design patterns
                    Provide alternate implementations
                    Handle change requests carefully



                  Essential complexity
                    Organize large APIs into smaller parts
                    Increase API granularity
                    Give up some control
                    Leave functionality out!



                                                              Slide 15
Agenda

 Introduction: Why it matters?
 Consider the perspective of the caller
 Keep it simple
 Strive for consistency
 Choose memorable names
 Specify the behaviour
 Make it safe
 Anticipate evolution
 Write helpful documentation




                                           Slide 16
Strive for consistency



                          Do the same thing the same way every
                          time
                          Rules, patterns, and conventions makes
                          everyday life more predictable
                          A consistent API has no frivolous or
                          unnecessary variations in it
                            int fscanf(FILE* stream, const char* format,...);
                            char* fgets(char* str, int num, FILE* stream);

                          Consistent APIs are easy to
                           learn, remember and use




                                                                             Slide 17
Strive for consistency

                          Follow established conventions!
                            C#:   IPublishable, PublishDocument()

                            Java: Publishable,   publishDocument()


                          Create your own conventions
                            eliminate unnecessary variations
                            parameter ordering, error handling, use of
                             null, etc.

                          Enforce consistency with code reviews
                          Use design patterns
                            Business Service – Business Object

                          Beware of false consistency
                            Attributes getAttributes() throws RemoteException




                                                                          Slide 18
Agenda

 Introduction: Why it matters?
 Consider the perspective of the caller
 Keep it simple
 Strive for consistency
 Choose memorable names
 Specify the behaviour
 Make it safe
 Anticipate evolution
 Write helpful documentation




                                           Slide 19
Choose memorable names

                     Avoid silly naming mistakes
                          antiquated naming conventions
                          spelling and grammar
                          synonyms
                          overly generic terms
                          inaccurate terms
                          meaningless terms

                     Choose names first
                          Design abstractions are difficult to name
                            – LLValue, DTree
                            – DocumentWrapperReferenceBuilderFactory
                          Best names come from the problem domain
                            – Familiar, intuitive, accurate, memorable
                          API as a domain-specific extension
                            – Establishing a domain vocabulary



                                                                         Slide 20
Choose memorable names

                     Survey problem domain for suitable names

                          “In online computer systems terminology, a tag is a non-
                           hierarchical keyword or term assigned to a piece of
                           information (such as an internet bookmark, digital
                           image, or computer file). This kind of metadata helps
                           describe an item and allows it to be found again by
                           browsing or searching. Tags are generally chosen
                           informally and personally by the item's creator or by its
                           viewer, depending on the system.”




                     Let names guide design

                         void assignTag(Item item, String tag);
                         Metadata describeItem(Item item);
                         Item[] searchByTag(String tag);



                                                                                   Slide 21
Agenda

 Introduction: Why it matters?
 Consider the perspective of the caller
 Keep it simple
 Strive for consistency
 Choose memorable names
 Specify the behaviour
 Make it safe
 Anticipate evolution
 Write helpful documentation




                                           Slide 22
Specify the behavior

                        Consider the class:
                       TeamsIdentifier
                         Uniquely identifies an Artesia entity.
                       Methods:
                          TeamsIdentifier(String id)

                             Constructs an identifier from a string.
                          java.lang.String asString()

                             Returns the id as a String.
                          TeamsIdentifier[] asTeamsIdArray()

                             Convenience method to return this id as an array.
                          boolean equals(java.lang.Object o)
                          boolean equalsId(TeamsIdentifier id)

                             Checks if two ids are equal.
                          java.lang.String getTeamsId()

                             Intended for hibernate use only.
                          java.lang.String toString()

                             Returns a string representation of the id.


                                                                                 Slide 23
Specify the behavior

                        Try answering the questions:
                       Expression                        True or False
                       TeamsIdentifier id1 = new
                       TeamsIdentifier(“name”);                ?
                       TeamsIdentifier id2 = new
                       TeamsIdentifier(“Name”);
                       id1.equals(id2)
                       id1.equalsId(id2);                      ?
                       id1.toString().equals(“name”)           ?
                       id1.getTeamsId.equals(“name”)           ?
                       TeamsIdentifier id = new
                       TeamsIdentifier(“a.b.c”)                ?
                       id.asTeamsIdArray().length == 3
                       TeamsIdentifier id = new
                       TeamsIdentifier(“a:b:c”)                ?
                       id.asTeamsIdArray().length == 3
                       AssetIdentifier assetId = new           ?
                       AssetIdentifier(“Donald”)
                       UserIdentifier userId = new
                       UserIdentifier(“Donald”)
                       assetId.equals(userId)
                       assetId.equalsId(userId)                ?




                                                                     Slide 24
Agenda

 Introduction: Why it matters?
 Consider the perspective of the caller
 Keep it simple
 Strive for consistency
 Choose memorable names
 Specify the behaviour
 Make it safe
 Anticipate evolution
 Write helpful documentation




                                           Slide 25
Make it safe

                Developers make mistakes
                Prevent access to dangerous code
                  Keep implementation code private
                  Prevent class extension
                  Control class initialization

                Prevent data corruption
                Maximize compiler checks
                Avoid out and in-out parameters
                Check arguments at runtime
                Provide informative error messages
                Make method calls atomic
                Write thread-safe code
                                                      Slide 26
Make it safe
               public Job {
                    private cancelling = false;
                    public void cancel() {
                    ...
                    cancelling = true;
                    onCancel();
                    cancelling = false;
                        ...
                    }
                    //Override this for custom cleanup when cancelling
                    protected void onCancel() {
                    }
                    public void execute() {
                    if(cancelling) throw
                   IllegalStateException(“Forbidden call to execute()
                   from onCancel()”);
                   ...
                    }
               }

                                                                    Slide 27
Agenda

 Introduction: Why it matters?
 Consider the perspective of the caller
 Keep it simple
 Strive for consistency
 Choose memorable names
 Specify the behaviour
 Make it safe
 Anticipate evolution
 Write helpful documentation




                                           Slide 28
Anticipate evolution

                        Maintain binary backwards compatibility
                          Clients work without an explicit upgrade
                          Technology-dependent compatibility rules
                             – Implemented Java interfaces not extensible
                             – Java constant values hard-coded in client code
                             – C++ has more compatibility issues than C
                             – Adding field or method breaks C++, not Java
                          Not the same as source-compatibility!

                        Maintain functional backwards compatibility
                          Allowed changes
                             – Weakening preconditions
                             – Strengthening postconditions
                             – Strengthening invariants
                          Testing is essential
                        SPIs evolve very differently from APIs
                                                                          Slide 29
Anticipate evolution

                        API versioning cannot be entirely avoided
                          major technology innovations
                          unanticipated requirements
                          quality degradation over time
                        Incompatible API = major API upgrade
                          Planned, not accidental
                          Significant new functionality
                          Cleanup and reorganization
                          Removal of deprecated constructs

                        Old API remains unchanged
                          must co-exist with the new API
                          Must be supported for years
                          often re-implemented as an Adaptor


                                                                Slide 30
Agenda

 Introduction: Why it matters?
 Consider the perspective of the caller
 Keep it simple
 Strive for consistency
 Choose memorable names
 Specify the behaviour
 Make it safe
 Anticipate evolution
 Write helpful documentation




                                           Slide 31
Write helpful documentation

                        FALSE: APIs are self documenting
                          Behavior
                          Design concepts and abstractions
                          Design patterns and conventions
                        TRUE: Nobody reads documentation
                          Just-in-time learning preferred
                          Documentation is referenced
                          Information can be hard to find
                        FALSE: Nobody uses documentation
                          Adobe Flex Online, July, 2008
                          24,293 programmers, 101,289 queries

                        TRUE: Users don’t want documentation
                          They want assistance (help)

                                                                 Slide 32
Write helpful documentation

                        Typical question from an online forum

                          Question: “With java.sql.ResultSet is there a
                           way to get a column's name as a String by
                           using the column's index? I had a look
                           through the API doc but I can't find anything.”


                          Answer: “See ResultSetMetaData:
                         ResultSet rs =
                           stmt.executeQuery("SELECT a, b, c
                           FROM TABLE2");
                         ResultSetMetaData rsmd =
                          rs.getMetaData();
                         String name =
                          rsmd.getColumnName(1);”



                                                                      Slide 33
Write helpful documentation

                        Think like a friend providing assistance
                          Write short sections (10 minutes or less)
                          Answer specific questions
                          Make it easy to find



                        Forms of API documentation
                          Developer’s Guide (overview)
                          Reference manual (details)
                          Cookbook (usage scenarios, code snippets)
                          Working code (test drive)
                          Tutorial (optional)
                          FAQ or Knowledge Base (ease of update)



                                                                       Slide 34
Summary


1) Consider the perspective of the caller
2) Keep it simple
3) Strive for consistency
4) Choose memorable names
5) Specify the behaviour
6) Make it safe
7) Anticipate evolution
8) Write helpful documentation

                                            Slide 35
Further reading:




                   The Amiable API
             http://theamiableapi.com




                                        Slide 36
Thank You




            Slide 37

More Related Content

What's hot

01 traditional analytics
01 traditional analytics01 traditional analytics
01 traditional analyticsMeasureWorks
 
Introduction to OSLC and Linked Data
Introduction to OSLC and Linked DataIntroduction to OSLC and Linked Data
Introduction to OSLC and Linked Dataopenservices
 
How to Design Frameworks
How to Design FrameworksHow to Design Frameworks
How to Design Frameworkselliando dias
 
Application Quality with Visual Studio 2010
Application Quality with Visual Studio 2010Application Quality with Visual Studio 2010
Application Quality with Visual Studio 2010Anna Russo
 
Pragmatic Not Dogmatic TDD Agile2012 by Joseph Yoder and Rebecca Wirfs-Brock
Pragmatic Not Dogmatic TDD Agile2012 by Joseph Yoder and Rebecca Wirfs-BrockPragmatic Not Dogmatic TDD Agile2012 by Joseph Yoder and Rebecca Wirfs-Brock
Pragmatic Not Dogmatic TDD Agile2012 by Joseph Yoder and Rebecca Wirfs-BrockJoseph Yoder
 
【中級編】実用レベルのLINE Botを爆速で! チャットボット開発者が絶対に知るべき3つのツボ
【中級編】実用レベルのLINE Botを爆速で! チャットボット開発者が絶対に知るべき3つのツボ【中級編】実用レベルのLINE Botを爆速で! チャットボット開発者が絶対に知るべき3つのツボ
【中級編】実用レベルのLINE Botを爆速で! チャットボット開発者が絶対に知るべき3つのツボYuji Ueki
 
Extending Appcelerator Titanium Mobile through Native Modules
Extending Appcelerator Titanium Mobile through Native ModulesExtending Appcelerator Titanium Mobile through Native Modules
Extending Appcelerator Titanium Mobile through Native Modulesomorandi
 
Introduction to Module Development with Appcelerator Titanium
Introduction to Module Development with Appcelerator TitaniumIntroduction to Module Development with Appcelerator Titanium
Introduction to Module Development with Appcelerator TitaniumAaron Saunders
 
2010 06-24 karlsruher entwicklertag
2010 06-24 karlsruher entwicklertag2010 06-24 karlsruher entwicklertag
2010 06-24 karlsruher entwicklertagMarcel Bruch
 
Epic.NET: Processes, patterns and architectures
Epic.NET: Processes, patterns and architecturesEpic.NET: Processes, patterns and architectures
Epic.NET: Processes, patterns and architecturesGiacomo Tesio
 
An Overview of Open Source & FOSS4G
An Overview of Open Source & FOSS4G An Overview of Open Source & FOSS4G
An Overview of Open Source & FOSS4G SANGHEE SHIN
 
Quality Best Practices & Toolkit for Enterprise Flex
Quality Best Practices & Toolkit for Enterprise FlexQuality Best Practices & Toolkit for Enterprise Flex
Quality Best Practices & Toolkit for Enterprise FlexFrançois Le Droff
 

What's hot (19)

01 traditional analytics
01 traditional analytics01 traditional analytics
01 traditional analytics
 
Introduction to OSLC and Linked Data
Introduction to OSLC and Linked DataIntroduction to OSLC and Linked Data
Introduction to OSLC and Linked Data
 
How to Design Frameworks
How to Design FrameworksHow to Design Frameworks
How to Design Frameworks
 
Java Technicalities
Java TechnicalitiesJava Technicalities
Java Technicalities
 
Application Quality with Visual Studio 2010
Application Quality with Visual Studio 2010Application Quality with Visual Studio 2010
Application Quality with Visual Studio 2010
 
Oops
OopsOops
Oops
 
Pragmatic Not Dogmatic TDD Agile2012 by Joseph Yoder and Rebecca Wirfs-Brock
Pragmatic Not Dogmatic TDD Agile2012 by Joseph Yoder and Rebecca Wirfs-BrockPragmatic Not Dogmatic TDD Agile2012 by Joseph Yoder and Rebecca Wirfs-Brock
Pragmatic Not Dogmatic TDD Agile2012 by Joseph Yoder and Rebecca Wirfs-Brock
 
【中級編】実用レベルのLINE Botを爆速で! チャットボット開発者が絶対に知るべき3つのツボ
【中級編】実用レベルのLINE Botを爆速で! チャットボット開発者が絶対に知るべき3つのツボ【中級編】実用レベルのLINE Botを爆速で! チャットボット開発者が絶対に知るべき3つのツボ
【中級編】実用レベルのLINE Botを爆速で! チャットボット開発者が絶対に知るべき3つのツボ
 
Android NDK: Entrando no Mundo Nativo
Android NDK: Entrando no Mundo NativoAndroid NDK: Entrando no Mundo Nativo
Android NDK: Entrando no Mundo Nativo
 
Extending Appcelerator Titanium Mobile through Native Modules
Extending Appcelerator Titanium Mobile through Native ModulesExtending Appcelerator Titanium Mobile through Native Modules
Extending Appcelerator Titanium Mobile through Native Modules
 
Introduction to Module Development with Appcelerator Titanium
Introduction to Module Development with Appcelerator TitaniumIntroduction to Module Development with Appcelerator Titanium
Introduction to Module Development with Appcelerator Titanium
 
Dot net 2005 vs 2003
Dot net 2005 vs 2003Dot net 2005 vs 2003
Dot net 2005 vs 2003
 
Cocoa fundamentalswert
Cocoa fundamentalswertCocoa fundamentalswert
Cocoa fundamentalswert
 
Acher PhD thesis defense
Acher PhD thesis defense Acher PhD thesis defense
Acher PhD thesis defense
 
2010 06-24 karlsruher entwicklertag
2010 06-24 karlsruher entwicklertag2010 06-24 karlsruher entwicklertag
2010 06-24 karlsruher entwicklertag
 
Testing on Android
Testing on AndroidTesting on Android
Testing on Android
 
Epic.NET: Processes, patterns and architectures
Epic.NET: Processes, patterns and architecturesEpic.NET: Processes, patterns and architectures
Epic.NET: Processes, patterns and architectures
 
An Overview of Open Source & FOSS4G
An Overview of Open Source & FOSS4G An Overview of Open Source & FOSS4G
An Overview of Open Source & FOSS4G
 
Quality Best Practices & Toolkit for Enterprise Flex
Quality Best Practices & Toolkit for Enterprise FlexQuality Best Practices & Toolkit for Enterprise Flex
Quality Best Practices & Toolkit for Enterprise Flex
 

Viewers also liked

Java util concurrent
Java util concurrentJava util concurrent
Java util concurrentRoger Xia
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threadingAPU
 
Alternate concurrency models
Alternate concurrency modelsAlternate concurrency models
Alternate concurrency modelsAbid Khan
 
Why both scrum and lean in dist dev 07092010
Why both scrum and lean in dist dev 07092010Why both scrum and lean in dist dev 07092010
Why both scrum and lean in dist dev 07092010Mads Troels Hansen
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
 
Best Coding Practices in Java and C++
Best Coding Practices in Java and C++Best Coding Practices in Java and C++
Best Coding Practices in Java and C++Nitin Aggarwal
 
(Ebook resume) job interview - 101 dynamite answers to interview questions ...
(Ebook   resume) job interview - 101 dynamite answers to interview questions ...(Ebook   resume) job interview - 101 dynamite answers to interview questions ...
(Ebook resume) job interview - 101 dynamite answers to interview questions ...Farahaa
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Haim Yadid
 
Inner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVAInner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVATech_MX
 
Data Structures- Part7 linked lists
Data Structures- Part7 linked listsData Structures- Part7 linked lists
Data Structures- Part7 linked listsAbdullah Al-hazmy
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresHitendra Kumar
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursionAbdullah Al-hazmy
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread poolsmaksym220889
 
Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014 Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014 iimjobs and hirist
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for vivaVipul Naik
 

Viewers also liked (20)

Multi threading
Multi threadingMulti threading
Multi threading
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
 
Alternate concurrency models
Alternate concurrency modelsAlternate concurrency models
Alternate concurrency models
 
Why both scrum and lean in dist dev 07092010
Why both scrum and lean in dist dev 07092010Why both scrum and lean in dist dev 07092010
Why both scrum and lean in dist dev 07092010
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
Best Coding Practices in Java and C++
Best Coding Practices in Java and C++Best Coding Practices in Java and C++
Best Coding Practices in Java and C++
 
(Ebook resume) job interview - 101 dynamite answers to interview questions ...
(Ebook   resume) job interview - 101 dynamite answers to interview questions ...(Ebook   resume) job interview - 101 dynamite answers to interview questions ...
(Ebook resume) job interview - 101 dynamite answers to interview questions ...
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014
 
Inner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVAInner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVA
 
Data Structures- Part7 linked lists
Data Structures- Part7 linked listsData Structures- Part7 linked lists
Data Structures- Part7 linked lists
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
 
Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014 Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014
 
Java SE 8 library design
Java SE 8 library designJava SE 8 library design
Java SE 8 library design
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for viva
 
Java codes
Java codesJava codes
Java codes
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 

Similar to Developer Friendly API Design

MongoDB for Java Developers with Spring Data
MongoDB for Java Developers with Spring DataMongoDB for Java Developers with Spring Data
MongoDB for Java Developers with Spring DataChris Richardson
 
MongoDB for Java Devs with Spring Data - MongoPhilly 2011
MongoDB for Java Devs with Spring Data - MongoPhilly 2011MongoDB for Java Devs with Spring Data - MongoPhilly 2011
MongoDB for Java Devs with Spring Data - MongoPhilly 2011MongoDB
 
Elements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code FirstElements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code FirstEnea Gabriel
 
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckCut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckTheo Jungeblut
 
Software Design for Testability
Software Design for TestabilitySoftware Design for Testability
Software Design for Testabilityamr0mt
 
IPC07 Talk - Beautiful Code with AOP and DI
IPC07 Talk - Beautiful Code with AOP and DIIPC07 Talk - Beautiful Code with AOP and DI
IPC07 Talk - Beautiful Code with AOP and DIRobert Lemke
 
Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofacmeghantaylor
 
Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp
Cut your Dependencies - Dependency Injection at Silicon Valley Code CampCut your Dependencies - Dependency Injection at Silicon Valley Code Camp
Cut your Dependencies - Dependency Injection at Silicon Valley Code CampTheo Jungeblut
 
Framework Engineering
Framework EngineeringFramework Engineering
Framework EngineeringYoungSu Son
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011YoungSu Son
 
What is the best approach to tdd
What is the best approach to tddWhat is the best approach to tdd
What is the best approach to tddLuca Mattia Ferrari
 
Cut your Dependencies with Dependency Injection for East Bay.NET User Group
Cut your Dependencies with Dependency Injection for East Bay.NET User Group Cut your Dependencies with Dependency Injection for East Bay.NET User Group
Cut your Dependencies with Dependency Injection for East Bay.NET User Group Theo Jungeblut
 
Java compilation
Java compilationJava compilation
Java compilationMike Kucera
 
API design
API designAPI design
API designsakpece
 
Lublin Startup Festival - Mobile Architecture Design Patterns
Lublin Startup Festival - Mobile Architecture Design PatternsLublin Startup Festival - Mobile Architecture Design Patterns
Lublin Startup Festival - Mobile Architecture Design PatternsKarol Szmaj
 

Similar to Developer Friendly API Design (20)

MongoDB for Java Developers with Spring Data
MongoDB for Java Developers with Spring DataMongoDB for Java Developers with Spring Data
MongoDB for Java Developers with Spring Data
 
MongoDB for Java Devs with Spring Data - MongoPhilly 2011
MongoDB for Java Devs with Spring Data - MongoPhilly 2011MongoDB for Java Devs with Spring Data - MongoPhilly 2011
MongoDB for Java Devs with Spring Data - MongoPhilly 2011
 
Elements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code FirstElements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code First
 
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckCut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
 
Software Design for Testability
Software Design for TestabilitySoftware Design for Testability
Software Design for Testability
 
Coding Naked
Coding NakedCoding Naked
Coding Naked
 
IPC07 Talk - Beautiful Code with AOP and DI
IPC07 Talk - Beautiful Code with AOP and DIIPC07 Talk - Beautiful Code with AOP and DI
IPC07 Talk - Beautiful Code with AOP and DI
 
Dependency Injection Styles
Dependency Injection StylesDependency Injection Styles
Dependency Injection Styles
 
Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofac
 
Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp
Cut your Dependencies - Dependency Injection at Silicon Valley Code CampCut your Dependencies - Dependency Injection at Silicon Valley Code Camp
Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp
 
Framework Engineering
Framework EngineeringFramework Engineering
Framework Engineering
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
 
What is the best approach to tdd
What is the best approach to tddWhat is the best approach to tdd
What is the best approach to tdd
 
Cut your Dependencies with Dependency Injection for East Bay.NET User Group
Cut your Dependencies with Dependency Injection for East Bay.NET User Group Cut your Dependencies with Dependency Injection for East Bay.NET User Group
Cut your Dependencies with Dependency Injection for East Bay.NET User Group
 
Java compilation
Java compilationJava compilation
Java compilation
 
200910 - iPhone at OOPSLA
200910 - iPhone at OOPSLA200910 - iPhone at OOPSLA
200910 - iPhone at OOPSLA
 
API design
API designAPI design
API design
 
ApiDesign
ApiDesignApiDesign
ApiDesign
 
Lublin Startup Festival - Mobile Architecture Design Patterns
Lublin Startup Festival - Mobile Architecture Design PatternsLublin Startup Festival - Mobile Architecture Design Patterns
Lublin Startup Festival - Mobile Architecture Design Patterns
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 

Recently uploaded

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 

Recently uploaded (20)

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 

Developer Friendly API Design

  • 1. API Design Ferenc Mihaly Senior Software Architect November 9, 2011 Slide 1 Copyright © Open Text Corporation. All rights reserved.
  • 2. Agenda  Introduction: Why it matters?  Consider the perspective of the caller  Keep it simple  Strive for consistency  Choose memorable names  Specify the behaviour  Make it safe  Anticipate evolution  Write helpful documentation Slide 2
  • 3. Agenda  Introduction: Why it matters?  Consider the perspective of the caller  Keep it simple  Strive for consistency  Choose memorable names  Specify the behaviour  Make it safe  Anticipate evolution  Write helpful documentation Slide 3
  • 4. Why it matters? “Software artifacts that cannot attract programmers are not reused, and fade into oblivion.” Brian Foote Slide 4
  • 5. Why it matters? “The impact of API design choices on users sometimes shows time penalties of a factor of 3 to 10.” Brad Myers Slide 5
  • 6. Why it matters? “Public APIs, like diamonds, are forever. You have one chance to get it right so give it your best .” Joshua Bloch Slide 6
  • 7. Why it matters? “A key lesson here is that API is not just a documented class. And, APIs don't just happen; they are a big investment..” Erich Gamma Slide 7
  • 8. Agenda  Introduction: Why it matters?  Consider the perspective of the caller  Keep it simple  Strive for consistency  Choose memorable names  Specify the behaviour  Make it safe  Anticipate evolution  Write helpful documentation Slide 8
  • 9. Consider the perspective of the caller  Implementation focus results in poor APIs: class ContentInstance java.lang.Object extended by DataObject extended by ManagedObject extended by ExtensibleObject extended by ContentItem extended by ContentInstance All Implemented Interfaces: IAttributedObject, IChannelAssociate, IPersistable, IRelatedAttribute, java.io.Serializable Slide 9
  • 10. Consider the perspective of the caller  Implementation perspective class Document { String getTag(); boolean isTagged(String tag); void remove(String tag); void removeTag(String tag); }  Caller perspective if(document.getTag().equals(“Best Practices”)) if(document.isTagged(“Best Practices”)) document.remove(“Best Practices”) document.removeTag(“Best Practices”) Slide 10
  • 11. Consider the perspective of the caller  Write client code first  Write client code for all major use cases  Ask yourself  Is this code simple?  Is this code intuitive?  Is this code consistent?  Is this code performant?  Does this code reveal any implementation details?  Not a wasted effort  Code samples reused in tests  Code samples reused in documentation Slide 11
  • 12. Agenda  Introduction: Why it matters?  Consider the perspective of the caller  Keep it simple  Strive for consistency  Choose memorable names  Specify the behaviour  Make it safe  Anticipate evolution  Write helpful documentation Slide 12
  • 13. Keep it simple “Simplicity is the ultimate sophistication” Leonardo da Vinci Slide 13
  • 14. Keep it Simple  Measuring Conceptual Complexity try { AuthenticationProvider20 provider = new LocalAuthenticationProvider19(); SearchCriteria18 criteria = new SearchCriteria17(EntityName16.USER15); criteria.addPropertyToFetch14(PropertyName13.COMMON_NAME12); criteria.addPropertyToFetch(PropertyName.PHONE11); criteria.addPropertyToMatch10(PropertyName.DEPARTMENT9, "R&D"); criteria.addPropertyToMatch(PropertyName.LOCATION8, "Waterloo"); criteria.setSortProperty7(PropertyName.COMMON_NAME); ProfileIterator6 iterator = provider.search5(criteria); while(iterator.hasNext()4){ Profile3 profile = iterator.next()2; Property1 commonName = profile.getProperty0(PropertyName.COMMON_NAME); Property phone = profile.getProperty(PropertyName.PHONE); System.out.println(commonName.getValue()-1, “ ”, phone.getValue()); } } catch(AuthenticationProviderException-2 e) { }  The higher score is better; less than zero means too complex! Slide 14
  • 15. Keep it simple  Accidental complexity  Avoid asking callers to extend classes  Avoid asking callers to implement interfaces  Avoid “Gang of Four” design patterns  Provide alternate implementations  Handle change requests carefully  Essential complexity  Organize large APIs into smaller parts  Increase API granularity  Give up some control  Leave functionality out! Slide 15
  • 16. Agenda  Introduction: Why it matters?  Consider the perspective of the caller  Keep it simple  Strive for consistency  Choose memorable names  Specify the behaviour  Make it safe  Anticipate evolution  Write helpful documentation Slide 16
  • 17. Strive for consistency  Do the same thing the same way every time  Rules, patterns, and conventions makes everyday life more predictable  A consistent API has no frivolous or unnecessary variations in it int fscanf(FILE* stream, const char* format,...); char* fgets(char* str, int num, FILE* stream);  Consistent APIs are easy to learn, remember and use Slide 17
  • 18. Strive for consistency  Follow established conventions!  C#: IPublishable, PublishDocument()  Java: Publishable, publishDocument()  Create your own conventions  eliminate unnecessary variations  parameter ordering, error handling, use of null, etc.  Enforce consistency with code reviews  Use design patterns  Business Service – Business Object  Beware of false consistency  Attributes getAttributes() throws RemoteException Slide 18
  • 19. Agenda  Introduction: Why it matters?  Consider the perspective of the caller  Keep it simple  Strive for consistency  Choose memorable names  Specify the behaviour  Make it safe  Anticipate evolution  Write helpful documentation Slide 19
  • 20. Choose memorable names  Avoid silly naming mistakes  antiquated naming conventions  spelling and grammar  synonyms  overly generic terms  inaccurate terms  meaningless terms  Choose names first  Design abstractions are difficult to name – LLValue, DTree – DocumentWrapperReferenceBuilderFactory  Best names come from the problem domain – Familiar, intuitive, accurate, memorable  API as a domain-specific extension – Establishing a domain vocabulary Slide 20
  • 21. Choose memorable names  Survey problem domain for suitable names  “In online computer systems terminology, a tag is a non- hierarchical keyword or term assigned to a piece of information (such as an internet bookmark, digital image, or computer file). This kind of metadata helps describe an item and allows it to be found again by browsing or searching. Tags are generally chosen informally and personally by the item's creator or by its viewer, depending on the system.”  Let names guide design void assignTag(Item item, String tag); Metadata describeItem(Item item); Item[] searchByTag(String tag); Slide 21
  • 22. Agenda  Introduction: Why it matters?  Consider the perspective of the caller  Keep it simple  Strive for consistency  Choose memorable names  Specify the behaviour  Make it safe  Anticipate evolution  Write helpful documentation Slide 22
  • 23. Specify the behavior  Consider the class: TeamsIdentifier Uniquely identifies an Artesia entity. Methods: TeamsIdentifier(String id) Constructs an identifier from a string. java.lang.String asString() Returns the id as a String. TeamsIdentifier[] asTeamsIdArray() Convenience method to return this id as an array. boolean equals(java.lang.Object o) boolean equalsId(TeamsIdentifier id) Checks if two ids are equal. java.lang.String getTeamsId() Intended for hibernate use only. java.lang.String toString() Returns a string representation of the id. Slide 23
  • 24. Specify the behavior  Try answering the questions: Expression True or False TeamsIdentifier id1 = new TeamsIdentifier(“name”); ? TeamsIdentifier id2 = new TeamsIdentifier(“Name”); id1.equals(id2) id1.equalsId(id2); ? id1.toString().equals(“name”) ? id1.getTeamsId.equals(“name”) ? TeamsIdentifier id = new TeamsIdentifier(“a.b.c”) ? id.asTeamsIdArray().length == 3 TeamsIdentifier id = new TeamsIdentifier(“a:b:c”) ? id.asTeamsIdArray().length == 3 AssetIdentifier assetId = new ? AssetIdentifier(“Donald”) UserIdentifier userId = new UserIdentifier(“Donald”) assetId.equals(userId) assetId.equalsId(userId) ? Slide 24
  • 25. Agenda  Introduction: Why it matters?  Consider the perspective of the caller  Keep it simple  Strive for consistency  Choose memorable names  Specify the behaviour  Make it safe  Anticipate evolution  Write helpful documentation Slide 25
  • 26. Make it safe  Developers make mistakes  Prevent access to dangerous code  Keep implementation code private  Prevent class extension  Control class initialization  Prevent data corruption  Maximize compiler checks  Avoid out and in-out parameters  Check arguments at runtime  Provide informative error messages  Make method calls atomic  Write thread-safe code Slide 26
  • 27. Make it safe public Job { private cancelling = false; public void cancel() { ... cancelling = true; onCancel(); cancelling = false; ... } //Override this for custom cleanup when cancelling protected void onCancel() { } public void execute() { if(cancelling) throw IllegalStateException(“Forbidden call to execute() from onCancel()”); ... } } Slide 27
  • 28. Agenda  Introduction: Why it matters?  Consider the perspective of the caller  Keep it simple  Strive for consistency  Choose memorable names  Specify the behaviour  Make it safe  Anticipate evolution  Write helpful documentation Slide 28
  • 29. Anticipate evolution  Maintain binary backwards compatibility  Clients work without an explicit upgrade  Technology-dependent compatibility rules – Implemented Java interfaces not extensible – Java constant values hard-coded in client code – C++ has more compatibility issues than C – Adding field or method breaks C++, not Java  Not the same as source-compatibility!  Maintain functional backwards compatibility  Allowed changes – Weakening preconditions – Strengthening postconditions – Strengthening invariants  Testing is essential  SPIs evolve very differently from APIs Slide 29
  • 30. Anticipate evolution  API versioning cannot be entirely avoided  major technology innovations  unanticipated requirements  quality degradation over time  Incompatible API = major API upgrade  Planned, not accidental  Significant new functionality  Cleanup and reorganization  Removal of deprecated constructs  Old API remains unchanged  must co-exist with the new API  Must be supported for years  often re-implemented as an Adaptor Slide 30
  • 31. Agenda  Introduction: Why it matters?  Consider the perspective of the caller  Keep it simple  Strive for consistency  Choose memorable names  Specify the behaviour  Make it safe  Anticipate evolution  Write helpful documentation Slide 31
  • 32. Write helpful documentation  FALSE: APIs are self documenting  Behavior  Design concepts and abstractions  Design patterns and conventions  TRUE: Nobody reads documentation  Just-in-time learning preferred  Documentation is referenced  Information can be hard to find  FALSE: Nobody uses documentation  Adobe Flex Online, July, 2008  24,293 programmers, 101,289 queries  TRUE: Users don’t want documentation  They want assistance (help) Slide 32
  • 33. Write helpful documentation  Typical question from an online forum  Question: “With java.sql.ResultSet is there a way to get a column's name as a String by using the column's index? I had a look through the API doc but I can't find anything.”  Answer: “See ResultSetMetaData: ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2"); ResultSetMetaData rsmd = rs.getMetaData(); String name = rsmd.getColumnName(1);” Slide 33
  • 34. Write helpful documentation  Think like a friend providing assistance  Write short sections (10 minutes or less)  Answer specific questions  Make it easy to find  Forms of API documentation  Developer’s Guide (overview)  Reference manual (details)  Cookbook (usage scenarios, code snippets)  Working code (test drive)  Tutorial (optional)  FAQ or Knowledge Base (ease of update) Slide 34
  • 35. Summary 1) Consider the perspective of the caller 2) Keep it simple 3) Strive for consistency 4) Choose memorable names 5) Specify the behaviour 6) Make it safe 7) Anticipate evolution 8) Write helpful documentation Slide 35
  • 36. Further reading: The Amiable API http://theamiableapi.com Slide 36
  • 37. Thank You Slide 37