Developer Friendly API Design

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
1 of 37

Recommended

Airbus Internship Presentation 2012 by
Airbus Internship Presentation 2012Airbus Internship Presentation 2012
Airbus Internship Presentation 2012Paveen Juntama
659 views47 slides
Framework Engineering_Final by
Framework Engineering_FinalFramework Engineering_Final
Framework Engineering_FinalYoungSu Son
1.4K views108 slides
Refactoring AOMs For AgilePT2010 by
Refactoring AOMs For AgilePT2010Refactoring AOMs For AgilePT2010
Refactoring AOMs For AgilePT2010Joseph Yoder
1.1K views60 slides
Design patterns difference between interview questions by
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questionsUmar Ali
10.4K views5 slides
Testing untestable code - oscon 2012 by
Testing untestable code - oscon 2012Testing untestable code - oscon 2012
Testing untestable code - oscon 2012Stephan Hochdörfer
2K views72 slides
Introduction to OSLC by
Introduction to OSLCIntroduction to OSLC
Introduction to OSLCopenservices
5.3K views53 slides

More Related Content

What's hot

01 traditional analytics by
01 traditional analytics01 traditional analytics
01 traditional analyticsMeasureWorks
599 views153 slides
Introduction to OSLC and Linked Data by
Introduction to OSLC and Linked DataIntroduction to OSLC and Linked Data
Introduction to OSLC and Linked Dataopenservices
4.5K views59 slides
How to Design Frameworks by
How to Design FrameworksHow to Design Frameworks
How to Design Frameworkselliando dias
588 views26 slides
Java Technicalities by
Java TechnicalitiesJava Technicalities
Java TechnicalitiesWen-Shih Chao
5.8K views59 slides
Application Quality with Visual Studio 2010 by
Application Quality with Visual Studio 2010Application Quality with Visual Studio 2010
Application Quality with Visual Studio 2010Anna Russo
748 views29 slides
Oops by
OopsOops
OopsPragya Rastogi
518 views44 slides

What's hot(19)

01 traditional analytics by MeasureWorks
01 traditional analytics01 traditional analytics
01 traditional analytics
MeasureWorks599 views
Introduction to OSLC and Linked Data by openservices
Introduction to OSLC and Linked DataIntroduction to OSLC and Linked Data
Introduction to OSLC and Linked Data
openservices4.5K views
How to Design Frameworks by elliando dias
How to Design FrameworksHow to Design Frameworks
How to Design Frameworks
elliando dias588 views
Application Quality with Visual Studio 2010 by Anna Russo
Application Quality with Visual Studio 2010Application Quality with Visual Studio 2010
Application Quality with Visual Studio 2010
Anna Russo748 views
Pragmatic Not Dogmatic TDD Agile2012 by Joseph Yoder and Rebecca Wirfs-Brock by Joseph Yoder
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
Joseph Yoder2.5K views
【中級編】実用レベルのLINE Botを爆速で! チャットボット開発者が絶対に知るべき3つのツボ by Yuji Ueki
【中級編】実用レベルのLINE Botを爆速で! チャットボット開発者が絶対に知るべき3つのツボ【中級編】実用レベルのLINE Botを爆速で! チャットボット開発者が絶対に知るべき3つのツボ
【中級編】実用レベルのLINE Botを爆速で! チャットボット開発者が絶対に知るべき3つのツボ
Yuji Ueki670 views
Extending Appcelerator Titanium Mobile through Native Modules by omorandi
Extending Appcelerator Titanium Mobile through Native ModulesExtending Appcelerator Titanium Mobile through Native Modules
Extending Appcelerator Titanium Mobile through Native Modules
omorandi10.6K views
Introduction to Module Development with Appcelerator Titanium by Aaron Saunders
Introduction to Module Development with Appcelerator TitaniumIntroduction to Module Development with Appcelerator Titanium
Introduction to Module Development with Appcelerator Titanium
Aaron Saunders6.4K views
2010 06-24 karlsruher entwicklertag by Marcel Bruch
2010 06-24 karlsruher entwicklertag2010 06-24 karlsruher entwicklertag
2010 06-24 karlsruher entwicklertag
Marcel Bruch3.1K views
Epic.NET: Processes, patterns and architectures by Giacomo Tesio
Epic.NET: Processes, patterns and architecturesEpic.NET: Processes, patterns and architectures
Epic.NET: Processes, patterns and architectures
Giacomo Tesio2.1K views
An Overview of Open Source & FOSS4G by SANGHEE SHIN
An Overview of Open Source & FOSS4G An Overview of Open Source & FOSS4G
An Overview of Open Source & FOSS4G
SANGHEE SHIN6K views
Quality Best Practices & Toolkit for Enterprise Flex by François Le Droff
Quality Best Practices & Toolkit for Enterprise FlexQuality Best Practices & Toolkit for Enterprise Flex
Quality Best Practices & Toolkit for Enterprise Flex
François Le Droff1.2K views

Viewers also liked

Multi threading by
Multi threadingMulti threading
Multi threadingMavoori Soshmitha
1.2K views78 slides
Java util concurrent by
Java util concurrentJava util concurrent
Java util concurrentRoger Xia
2.3K views62 slides
12 multi-threading by
12 multi-threading12 multi-threading
12 multi-threadingAPU
888 views16 slides
Alternate concurrency models by
Alternate concurrency modelsAlternate concurrency models
Alternate concurrency modelsAbid Khan
486 views24 slides
Why both scrum and lean in dist dev 07092010 by
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
2.1K views24 slides
Inter threadcommunication.38 by
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
2.5K views22 slides

Viewers also liked(20)

Java util concurrent by Roger Xia
Java util concurrentJava util concurrent
Java util concurrent
Roger Xia2.3K views
12 multi-threading by APU
12 multi-threading12 multi-threading
12 multi-threading
APU888 views
Alternate concurrency models by Abid Khan
Alternate concurrency modelsAlternate concurrency models
Alternate concurrency models
Abid Khan486 views
Why both scrum and lean in dist dev 07092010 by Mads Troels Hansen
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
Mads Troels Hansen2.1K views
Inter threadcommunication.38 by myrajendra
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
myrajendra2.5K views
Best Coding Practices in Java and C++ by Nitin Aggarwal
Best Coding Practices in Java and C++Best Coding Practices in Java and C++
Best Coding Practices in Java and C++
Nitin Aggarwal853 views
(Ebook resume) job interview - 101 dynamite answers to interview questions ... by Farahaa
(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 ...
Farahaa33.7K views
Concurrency and Multithreading Demistified - Reversim Summit 2014 by Haim Yadid
Concurrency and Multithreading Demistified - Reversim Summit 2014Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014
Haim Yadid1.9K views
Inner Classes & Multi Threading in JAVA by Tech_MX
Inner Classes & Multi Threading in JAVAInner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVA
Tech_MX4.5K views
Advanced Introduction to Java Multi-Threading - Full (chok) by choksheak
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
choksheak12.1K views
Java Performance, Threading and Concurrent Data Structures by Hitendra Kumar
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
Hitendra Kumar11.6K views
Java concurrency - Thread pools by maksym220889
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
maksym2208895.6K views
Top 10 Java Interview Questions and Answers 2014 by iimjobs and hirist
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 hirist10.5K views
Java questions for viva by Vipul Naik
Java questions for vivaJava questions for viva
Java questions for viva
Vipul Naik60.4K views

Similar to Developer Friendly API Design

MongoDB for Java Developers with Spring Data by
MongoDB for Java Developers with Spring DataMongoDB for Java Developers with Spring Data
MongoDB for Java Developers with Spring DataChris Richardson
5.4K views44 slides
MongoDB for Java Devs with Spring Data - MongoPhilly 2011 by
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
6.9K views44 slides
Elements of DDD with ASP.NET MVC & Entity Framework Code First by
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
7.6K views27 slides
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck by
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
1.5K views43 slides
Software Design for Testability by
Software Design for TestabilitySoftware Design for Testability
Software Design for Testabilityamr0mt
7.2K views22 slides
Coding Naked by
Coding NakedCoding Naked
Coding NakedCaleb Jenkins
3.7K views80 slides

Similar to Developer Friendly API Design(20)

MongoDB for Java Developers with Spring Data by Chris Richardson
MongoDB for Java Developers with Spring DataMongoDB for Java Developers with Spring Data
MongoDB for Java Developers with Spring Data
Chris Richardson5.4K views
MongoDB for Java Devs with Spring Data - MongoPhilly 2011 by MongoDB
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
MongoDB6.9K views
Elements of DDD with ASP.NET MVC & Entity Framework Code First by Enea Gabriel
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
Enea Gabriel7.6K views
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck by Theo Jungeblut
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
Theo Jungeblut1.5K views
Software Design for Testability by amr0mt
Software Design for TestabilitySoftware Design for Testability
Software Design for Testability
amr0mt7.2K views
IPC07 Talk - Beautiful Code with AOP and DI by Robert Lemke
IPC07 Talk - Beautiful Code with AOP and DIIPC07 Talk - Beautiful Code with AOP and DI
IPC07 Talk - Beautiful Code with AOP and DI
Robert Lemke1K views
Dependency Injection and Autofac by meghantaylor
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofac
meghantaylor5.3K views
Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp by Theo Jungeblut
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
Theo Jungeblut516 views
Framework Engineering by YoungSu Son
Framework EngineeringFramework Engineering
Framework Engineering
YoungSu Son1.5K views
Framework engineering JCO 2011 by YoungSu Son
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
YoungSu Son1.6K views
Cut your Dependencies with Dependency Injection for East Bay.NET User Group by Theo Jungeblut
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 Jungeblut999 views
Java compilation by Mike Kucera
Java compilationJava compilation
Java compilation
Mike Kucera956 views
API design by sakpece
API designAPI design
API design
sakpece81 views
Lublin Startup Festival - Mobile Architecture Design Patterns by Karol Szmaj
Lublin Startup Festival - Mobile Architecture Design PatternsLublin Startup Festival - Mobile Architecture Design Patterns
Lublin Startup Festival - Mobile Architecture Design Patterns
Karol Szmaj588 views

Recently uploaded

"Surviving highload with Node.js", Andrii Shumada by
"Surviving highload with Node.js", Andrii Shumada "Surviving highload with Node.js", Andrii Shumada
"Surviving highload with Node.js", Andrii Shumada Fwdays
49 views29 slides
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T by
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&TCloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&TShapeBlue
81 views34 slides
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ... by
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...ShapeBlue
114 views12 slides
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue by
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueWhat’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueShapeBlue
191 views23 slides
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue by
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlueCloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlueShapeBlue
63 views15 slides
Network Source of Truth and Infrastructure as Code revisited by
Network Source of Truth and Infrastructure as Code revisitedNetwork Source of Truth and Infrastructure as Code revisited
Network Source of Truth and Infrastructure as Code revisitedNetwork Automation Forum
49 views45 slides

Recently uploaded(20)

"Surviving highload with Node.js", Andrii Shumada by Fwdays
"Surviving highload with Node.js", Andrii Shumada "Surviving highload with Node.js", Andrii Shumada
"Surviving highload with Node.js", Andrii Shumada
Fwdays49 views
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T by ShapeBlue
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&TCloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T
ShapeBlue81 views
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ... by ShapeBlue
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...
ShapeBlue114 views
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue by ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueWhat’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
ShapeBlue191 views
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue by ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlueCloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
ShapeBlue63 views
Data Integrity for Banking and Financial Services by Precisely
Data Integrity for Banking and Financial ServicesData Integrity for Banking and Financial Services
Data Integrity for Banking and Financial Services
Precisely76 views
The Power of Heat Decarbonisation Plans in the Built Environment by IES VE
The Power of Heat Decarbonisation Plans in the Built EnvironmentThe Power of Heat Decarbonisation Plans in the Built Environment
The Power of Heat Decarbonisation Plans in the Built Environment
IES VE67 views
Business Analyst Series 2023 - Week 4 Session 7 by DianaGray10
Business Analyst Series 2023 -  Week 4 Session 7Business Analyst Series 2023 -  Week 4 Session 7
Business Analyst Series 2023 - Week 4 Session 7
DianaGray10110 views
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online by ShapeBlue
KVM Security Groups Under the Hood - Wido den Hollander - Your.OnlineKVM Security Groups Under the Hood - Wido den Hollander - Your.Online
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online
ShapeBlue154 views
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by Network Automation Forum
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R... by ShapeBlue
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...
ShapeBlue105 views
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O... by ShapeBlue
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...
Declarative Kubernetes Cluster Deployment with Cloudstack and Cluster API - O...
ShapeBlue59 views
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda... by ShapeBlue
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
ShapeBlue93 views
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue by ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueElevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
ShapeBlue149 views
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ... by ShapeBlue
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...
ShapeBlue97 views
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue by ShapeBlue
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlueCloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue
ShapeBlue68 views

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