JavaScript API 設計原則

轉自:http://jinlong.github.io/2015/08/31/secrets-of-awesome-javascript-api-design/

前段時間組織優化我們的原生模塊 API(iOS、Android 模塊封裝成 JavaScript 接口),於是學習了幾篇 JavaScript API 設計的文章,儘管是舊文,但受益匪淺,這裏記錄一下。


好的 API 設計:在自描述的同時,達到抽象的目標。

設計良好的 API ,開發者可以快速上手,沒必要經常抱着手冊和文檔,也沒必要頻繁光顧技術支持社區。

流暢的接口

方法鏈:流暢易讀,更易理解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 常見的 API 調用方式:改變一些顏色,添加事件監聽
var elem = document.getElementById("foobar");
elem.style.background = "red";
elem.style.color = "green";
elem.addEventListener('click', function(event) {
  alert("hello world!");
}, true);

//(設想的)方法鏈 API
DOMHelper.getElementById('foobar')
  .setStyle("background", "red")
  .setStyle("color", "green")
  .addEvent("click", function(event) {
    alert("hello world");
  });

設置和獲取操作,可以合二爲一;方法越多,文檔可能越難寫

1
2
3
4
5
6
7
8
9
10
var $elem = jQuery("#foobar");

//setter
$elem.setCss("background", "green");
//getter
$elem.getCss("color") === "red";

//getter, setter 合二爲一
$elem.css("background", "green");
$elem.css("color") === "red";

一致性

相關的接口保持一致的風格,一整套 API 如果傳遞一種熟悉和舒適的感覺,會大大減輕開發者對新工具的適應性。

命名這點事:既要短,又要自描述,最重要的是保持一致性

“There are only two hard problems in computer science: cache-invalidation and naming things.”
“在計算機科學界只有兩件頭疼的事:緩存失效和命名問題”
— Phil Karlton

選擇一個你喜歡的措辭,然後持續使用。選擇一種風格,然後保持這種風格。

處理參數

需要考慮大家如何使用你提供的方法,是否會重複調用?爲何會重複調用?你的 API 如何幫助開發者減少重複的調用?
接收 map 映射參數,回調或者序列化的屬性名,不僅讓你的 API 更乾淨,而且使用起來更舒服、高效。

jQuery 的 css() 方法可以給 DOM 元素設置樣式:

1
2
3
4
5
jQuery("#some-selector")
  .css("background", "red")
  .css("color", "white")
  .css("font-weight", "bold")
  .css("padding", 10);

這個方法可以接受一個 JSON 對象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
jQuery("#some-selector").css({
  "background" : "red",
  "color" : "white",
  "font-weight" : "bold",
  "padding" : 10
});

// 通過傳一個 map 映射綁定事件
jQuery("#some-selector").on({
  "click" : myClickHandler,
  "keyup" : myKeyupHandler,
  "change" : myChangeHandler
});

// 爲多個事件綁定同一個處理函數
jQuery("#some-selector").on("click keyup change", myEventHandler);

處理類型

定義方法的時候,需要決定它可以接收什麼樣的參數。我們不清楚人們如何使用我們的代碼,但可以更有遠見,考慮支持哪些參數類型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 原來的代碼
DateInterval.prototype.days = function(start, end) {
  return Math.floor((end - start) / 86400000);
};

// 修改後的代碼
DateInterval.prototype.days = function(start, end) {
  if (!(start instanceof Date)) {
    start = new Date(start);
  }
  if (!(end instanceof Date)) {
    end = new Date(end);
  }

  return Math.floor((end.getTime() - start.getTime()) / 86400000);
};

加了短短的 6 行代碼,我們的方法強大到可以接收 Date 對象,數字的時間戳,甚至像Sat Sep 08 2012 15:34:35 GMT+0200 (CEST) 這樣的字符串。

如果你需要確保傳入的參數類型(字符串,數字,布爾),可以這樣轉換:

1
2
3
4
5
function castaway(some_string, some_integer, some_boolean) {
  some_string += "";
  some_integer += 0; // parseInt(some_integer, 10) 更安全些
  some_boolean = !!some_boolean;
}

處理 undefined

爲了使你的 API 更健壯,需要鑑別是否真正的 undefined 值被傳遞進來,可以檢查 arguments 對象:

1
2
3
4
5
6
7
8
9
10
11
12
13
function testUndefined(expecting, someArgument) {
  if (someArgument === undefined) {
    console.log("someArgument 是 undefined");
  }
  if (arguments.length > 1) {
    console.log(" 然而它實際是傳進來的 ");
  }
}

testUndefined("foo");
// 結果: someArgument 是 undefined
testUndefined("foo", undefined);
// 結果:  someArgument 是 undefined , 然而它實際是傳進來的

給參數命名

1
2
3
4
5
event.initMouseEvent(
  "click", true, true, window,
  123, 101, 202, 101, 202,
  true, false, false, false,
  1, null);

Event.initMouseEvent 這個方法簡直喪心病狂,不看文檔的話,誰能說出每個參數是什麼意思?

給每個參數起個名字,賦個默認值,可好

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
event.initMouseEvent(
  type="click",
  canBubble=true,
  cancelable=true,
  view=window,
  detail=123,
  screenX=101,
  screenY=202,
  clientX=101,
  clientY=202,
  ctrlKey=true,
  altKey=false,
  shiftKey=false,
  metaKey=false,
  button=1,
  relatedTarget=null);

ES6, 或者 Harmony 就有 默認參數值 和 rest 參數 了。

參數接收 JSON 對象

與其接收一堆參數,不如接收一個 JSON 對象:

1
2
3
4
5
6
7
8
9
10
11
12
function nightmare(accepts, async, beforeSend, cache, complete, /* 等 28 個參數 */) {
  if (accepts === "text") {
    // 準備接收純文本
  }
}

function dream(options) {
  options = options || {};
  if (options.accepts === "text") {
    // 準備接收純文本
  }
}

調用起來也更簡單了:

1
2
3
4
5
6
7
nightmare("text", true, undefined, false, undefined, /* 等 28 個參數 */);

dream({
  accepts: "text",
  async: true,
  cache: false
});

參數默認值

參數最好有默認值,通過 jQuery.extend() , _.extend() 和 Protoype 的 Object.extend,可以覆蓋預設的默認值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var default_options = {
  accepts: "text",
  async: true,
  beforeSend: null,
  cache: false,
  complete: null,
  // …
};

function dream(options) {
  var o = jQuery.extend({}, default_options, options || {});
  console.log(o.accepts);
}

dream({ async: false });
// prints: "text"

擴展性

回調(callbacks)

通過回調, API 用戶可以覆蓋你的某一部分代碼。把一些需要自定義的功能開放成可配置的回調函數,允許 API 用戶輕鬆覆蓋你的默認代碼。

API 接口一旦接收回調,確保在文檔中加以說明,並提供代碼示例。

事件(events)

事件接口最好見名知意,可以自由選擇事件名字,避免與原生事件 重名。

處理錯誤

不是所有的錯誤都對開發者調試代碼有用:

1
2
3
4
5
6
// jQuery 允許這麼寫
$(document.body).on('click', {});

// 點擊時報錯
//   TypeError: ((p.event.special[l.origType] || {}).handle || l.handler).apply is not a function
//   in jQuery.min.js on Line 3

這樣的錯誤調試起來很痛苦,不要浪費開發者的時間,直接告訴他們犯了什麼錯:

1
2
3
if (Object.prototype.toString.call(callback) !== '[object Function]') { // 看備註
  throw new TypeError("callback is not a function!");
}

備註:typeof callback === "function" 在老的瀏覽器上會有問題,object 會當成個function 。

可預測性

好的 API 具有可預測性,開發者可以根據例子推斷它的用法。

Modernizr’s 特性檢測 是個例子:

a) 它使用的屬性名完全與 HTML5、CSS 概念和 API 相匹配

b) 每一個單獨的檢測一致地返回 true 或 false 值

1
2
3
4
5
6
7
8
// 所有這些屬性都返回 'true' 或 'false'
Modernizr.geolocation
Modernizr.localstorage
Modernizr.webworkers
Modernizr.canvas
Modernizr.borderradius
Modernizr.boxshadow
Modernizr.flexbox

依賴於開發者已熟悉的概念也可以達到可預測的目的。

jQuery’s 選擇器語法 就是一個顯著的例子,CSS1-CSS3 的選擇器可直接用於它的 DOM 選擇器引擎。

1
2
3
$("#grid") // Selects by ID
$("ul.nav > li") // All LIs for the UL with class "nav"
$("ul li:nth-child(2)") // Second item in each list

比例協調

好的 API 並不一定是小的 API,API 的體積大小要跟它的功能相稱。

比如 Moment.js,著名的日期解析和格式化的庫,可以稱之爲均衡,它的 API 既簡潔又功能明確。

像 Moment.js 這樣特定功能的庫,確保 API 的專注和小巧非常重要。

編寫 API 文檔

軟件開發最艱難的任務之一是寫文檔,實際上每個人都恨寫文檔,怨聲載道的是沒有一個好用的文檔工具。

以下是一些文檔自動生成工具:

最重要的是:確保文檔跟代碼同步更新。

參考資料:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章