Effective API Design

*/-->

div.org-src-container {
font-size: 85%;
font-family: monospace;
}

A well-written API can be a great asset to the organization that wrote it and to all that
use it. Given the importance of good API design, surprisingly little has been written on the
subject. In this talk (recorded at Javapolis), Java library designer Joshua Bloch teaches
how to design good APIs, with many examples of what good and bad APIs look like.

From: Infoq.com

1 Foreword

  • Why is API Design Important?
  • APIs can be among a company's greates assets.
    • Customers invest heavily: buying, writing, learning.
    • Cost to stop using an API can be prohibitive
    • Successful public APIs capture customers.
  • Can also be among company's greatest liabilities
    • bad APIs result in unending stream of support calls.
  • Public APIs are forever
    • One chance to get it right.
    • Why is API Design Important to You?
  • If you program, you are an API Designer
    • Good code is modular - each module has an API
  • Usefull modules tend to get reused
    • Once module has users, can't change API at will

      • You can add new ones,
      • But you should not delete or modify existing ones at will.
  • Thinking in tersm of API improves code quality.
  • Characteristics of a Good API
  • Easy to learn.
  • Easy to use, Hard to misuse
  • Easy to read and maintian code that uses it
  • Sufficiently powerful to satisfy requirements.
  • Easy to extend
  • Appropriate to audience.

2 Process of API Design

  • Gather requirements - with a Healthy Degree of Skepticism
    Often you'll get proposed solutions instead, but better solutions may existing, and your job
    is to extract true requirements from the use-cases.

    And, keep in mind that it can be easier and more rewarding to build somthing more general.

  • Make spec short: single page is okey
  • Write to Your API Early and Often
  • Writing to SPI is Even More Important
    • Service Provider Interface (SPI)
    • Plugin-in interface enabling multiple implementations
    • Example: Java Cryptography Extension (JCE).
    • Write multiple plugins before release
    • The Rule of threes.
  • Maintain Realistic Expectations

3 General Principles

  • API should do one thing and do it well
  • Functionality should be easy to explain:
    • If it's hard to name, that generaty a bad sign.
    • Good names drive development.
    • Be amenable to spliting and merging modules.
  • API should be as mall as possible, but no smaller
    • API should satisfy its requirements
    • When in doubt, leave it out!
      • You can always add, but you can never remove!
    • Conceptual weight more important than bulk.
    • Look for a good power-to-weight ratio
  • Implementation should not impact API
  • Minimize Accessibility of Everything
    • Make classes and members as private as possible.
    • Public classes should have no public fields.
    • Maximizes information hiding
    • Allow modules to be used, understood, built, tested, and debugged independently.
  • Names Matter – API is a Little Language
    • Names shoudl be Largely Self-Explanatory
    • Be consistent – same word meas same thing
    • Be regular – strive for symmetry
    • Code should read like prose
  • Documentation Matters
  • Document Religiosly:
    All public APIs should have Documentation:

    • Classes: what an instance represents
    • Method: contract between method and its client
      • Preconditions, postconditions, side-effects.
    • Parameter: indicat units, form, ownership
    • Document state space very carefully
  • Consider Performace Consequences of API Design Decisions

    • bad decisions can limit performance.
  • API Must Coexist Peacefully with Platform

4 Classes Deisgn

  • Minimize Mutability
    Classes should be immutable unless there's a good reason to do otherwise. If mutable,
    keep state-space small, well-defined.
  • Subcalss only where it makes sense
    Subclassing implies subsitituability,

    • Public classses should not subclasses other public classes.
  • Design and Document for Inheritance or Else Prohibit it!

5 Method Design

  • Don't make the Client Do Anything the Module Could Do
  • Don't Violate Principle of Least Astonishment
  • Fail Fast – Report Errors as Sonn as Possible After They Occur
  • Provide Programmatic Access to All Data Available in String Form
  • Overload With Care

if you must provide ambiguous overloadings, ensure same behavior for same arguments.

  • Use Appropriate Parameter and Return Types

    • Favor interface types over classes for input.
    • Use most specifi possible input parameter type

    Moves error from runtime to compile time.

    • Don't use string if a better type exists
    • Do't use floating point for monetary values:

    Binary floating point causes inexact result.

    • Use double (64 bits) rather than float(32 bits):

    Precision loss is real, performance loss negligible.

  • Use Consistent parameter Ordering Across Methods
#include <string.h>
char *strcpy(char *dest, char *src);
void bcopy (void* src, void* dst, int n); // XXX: Bad example!
  • Avoid Long Parameter Lists

    • Three or fewer parameters is ideal
    • Two techniques for shortening parameter lists:
      • Break up method
      • Create helper class to hold parameters
  • Avoid Return Values that Demand Exceptional Processing

6 Exceptions Design

  • Throw Exceptions to Indicate Exceptional Conditions

    • Don't force client to use exceptions for control flow.
    • Don't fail silently
  • Favor Unchecked Exceptions
  • Include Failure-Capture Information in Exceptions

7 Refactoring API Design

Just some examples….

Effective API Design的更多相关文章

  1. API Design

    REST API Design Guidelines V 1.0.201208 Draft 5 Last Updated: 08/31/2012 1       简介 本文档旨在规范REST API的 ...

  2. Principles of good RESTful API Design 好的 RESTful API 设计

    UPDATE: This post has been expanded upon and converted into an eBook. Good API design is hard! An AP ...

  3. RESTful API Design With NodeJS & Restify

    http://code.tutsplus.com/tutorials/restful-api-design-with-nodejs-restify--cms-22637 The RESTful API ...

  4. API Design Principles -- QT Project

    [the original link] One of Qt’s most reputed merits is its consistent, easy-to-learn, powerfulAPI. T ...

  5. Atitit.index manager api design 索引管理api设计

    Atitit.index manager api design 索引管理api设计 1. kw 1 1.1. 索引类型 unique,normal,fulltxt 1 1.2. 聚集索引(cluste ...

  6. Atitit.index manager api design 索引管理api设计

    Atitit.index manager api design 索引管理api设计 1. kw1 1.1. 索引类型 unique,normal,fulltxt1 1.2. 聚集索引(clustere ...

  7. RESTful API Design: 13 Best Practices to Make Your Users Happy

    RESTful API Design: 13 Best Practices to Make Your Users Happy First step to the RESTful way: make s ...

  8. Web API design

    Web API design 28 minutes to read Most modern web applications expose APIs that clients can use to i ...

  9. Google API Design Guide (谷歌API设计指南)中文版

    面向资源的设计 这份设计指南的目标是帮助开发人员设计简单.一致.易用的网络API.同时,它也有助于收敛基于socket的API和(注:原文是with,这里翻译为“和”)基于HTTP的REST API. ...

随机推荐

  1. python小专题——urllib2模块

    Python 标准库中有很多实用的工具类,但是在具体使用时,标准库文档上对使用细节描述的并不清楚,比如 urllib2 这个 HTTP 客户端库.这里总结了一些 urllib2 库的使用细节. 1 P ...

  2. Codeforces Round #426 (Div. 2) D 线段树优化dp

    D. The Bakery time limit per test 2.5 seconds memory limit per test 256 megabytes input standard inp ...

  3. R语言的ARIMA模型预测

    R通过RODBC连接数据库 stats包中的st函数建立时间序列 funitRoot包中的unitrootTest函数检验单位根 forecast包中的函数进行预测 差分用timeSeries包中di ...

  4. python中的常用模块(2)

    在自动化测试中,经常需要查找操作文件,比如说查找配置文件(从而读取配置文件的信息),查找测试报告(从而发送测试报告邮件), 经常要对大量文件和大量路径进行操作,这就依赖于os模块. 1.当前路径及路径 ...

  5. linux下安装python和pip

    注意:不要轻易去卸载原有的python环境,因为有些软件是依赖他的 一:安装前,先将依赖环境一并安装,避免后面重复编译 [root@redhat2 bin]# yum install gcc g++ ...

  6. Jmeter javaRequest插件开发

    1. 适用场景 Jmeter工具当前支持的协议或协议所支持的传输方式及传输内容不能满足当前项目的测试要求时,就需要根据实际要求手动编写java测试代码(实现对应的Jmeter规范),以插件方式加载到J ...

  7. asp启用父路径

    开启父路径后可以用../来表示上一层目录,如果网站程序中使用了../,不开启则网站程序里有../就会报错. IIS6启用父路径方法:打开IIS管理器——网站——右键属性——主目录——配置——选项——选 ...

  8. [转载]asp.net mvc: why is Html.CheckBox generating an additional hidden input

    http://stackoverflow.com/questions/2697299/asp-net-mvc-why-is-html-checkbox-generating-an-additional ...

  9. IE6下面的css调试工具

    在开发过程中,代码部分实现之后,就要着手于前台展示部分的界面,公司的美工又是新手,无奈,只有自己慢慢调了,但IE6之前的版本都没有好的调试工具,后来在网上搜索了一个 IE Developer Tool ...

  10. 51nod 小Z的trie(Trie+广义SAM)

    [题目链接] http://www.51nod.com/contest/problem.html#!problemId=1647 [题意] 给定一个n个字符串的Trie,每次询问一个字符串在Trie上 ...