API
API
API
Application Programming Interface
Source code interface
For
library or OS
Provides services to a program
more complete
Characteristics of Good
APIs
Easy to learn
Easy to use even without documentation
Hard to misuse
Easy to read and maintain code that uses it
Sufficiently powerful to satisfy requirements
Easy to extend
Appropriate to audience
Designing an API
Gather requirements
Dont gather solutions
Extract true requirements
Collect specific scenarios where it will be used
Hints:
Write plugins/use examples before fully designed and
implemented
Expect it to evolve
Broad Issues to
Consider in Design
1. Interface
2. Resource Management
3. Error Handling
Information Hiding
How much detail is exposed
Impacts all three of the above
1. Interface Principles
Simple
General
Regular
Predictable
Robust
Adaptable
Simple
Users have to understand!
Do one thing and do it well
General
Implementation can change, API cant
Hide Information!
Dont let implementation detail leak into API
Minimize accessibility (e.g. private classes and
members)
Implementation details can confuse users
Regular
Do the same thing the same way everywhere
Names matter
Self explanatory
Consistent across API
Predictable
Dont violate the principle of Least
Astonishment
User
Predictable
Try to minimize use of other interfaces
Make
as self-contained as possible
Be explicit about external services required
Document!
Every
Robust
Able to deal with unexpected input
Error Handling (see later)
Adaptable
API can be extended, but never
shortened
Heavily
Information Hiding
Implementation
API
2. Resource Management
Determine which side is responsible for
Initialization
Maintaining state
Sharing and copying
Cleaning up
Various resources
Memory
Files
Global variables
Resource Management
Generally, free resources where they were
allocated
Return references or copies?
3. Error Handling
Catch errors, dont ignore them
Print message and fail is not always good
Especially in APIs
Need to allow programs to recover or save data
Fail Fast
Report as soon as an error occurs
Sometimes even at compile time!
Use
Error Management
Return values
Should be in form the calling function can use
Return as much useful information as possible
Sentinel values only work if function cannot return all
possible values of that type
Define pairs, or return another parameter to indicate
errors
Exceptions
Generally indicate a programming error
Programming construct
Set exception value (e.g. as return)
Other program operation when exception thrown
Exceptions usually in global registry
Exceptions
Only use in truly exceptional situations
Never