API Design: CPSC 315 - Programming Studio Spring 2009
API Design: CPSC 315 - Programming Studio Spring 2009
Document!
⚫ Every class, method, interface, constructor,
parameter, exception
⚫ When states are kept, this should be very
clearly documented
Robust
Able to deal with unexpected input
Error Handling (see later)
Adaptable
API can be extended, but never
shortened
⚫ Heavily used APIs likely will be extended
Information Hiding
⚫ Implementation details should not affect
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?
⚫ Can have huge performance and ease of use
impact
Multi-threaded code makes this especially
critical
⚫ Reentrant: works regardless of number of
simultaneous executions
⚫ Avoid using anything (globals, static locals, other
modifications) that others could also use
⚫ Locks can be important
3. Error Handling
Catch errors, don’t ignore them
“Print message and fail” is not always good
⚫ Especially in APIs
⚫ Need to allow programs to recover or save data
Detect at low level, but handle at high level
⚫ Generally, error should be handled by calling
routine
⚫ The callee can leave things in a “nice” state for
recovery, though
⚫ Keep things usable in case the caller can recover
Fail Fast
Report as soon as an error occurs
Sometimes even at compile time!
⚫ Use of static types, generics
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
Use error “wrapper function” if needed
⚫ Consistent way of marking, reporting error status
⚫ Encourages use
⚫ But, can add complexity
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
Include information about failure
⚫ For repair and debugging
Exceptions should generally be unchecked
⚫ Automatically process globally, rather than require
explicit checks over and over
Exceptions
Only use in truly exceptional situations
⚫ Never use as a control structure
⚫ The modern GOTO