前段時間組織優化我們的原生模組 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 文件
軟體開發最艱難的任務之一是寫文件,實際上每個人都恨寫文件,怨聲載道的是沒有一個好用的文件工具。
以下是一些文件自動生成工具:
- YUIDoc (requires Node.js, npm)
- JsDoc Toolkit (requires Node.js, npm)
- Markdox (requires Node.js, npm)
- Dox (requires Node.js, npm)
- Docco (requires Node.js, Python, CoffeeScript)
- JSDuck (reqires Ruby, gem)
- JSDoc 3 (requires Java)
最重要的是:確保文件跟程式碼同步更新。
參考資料:
打賞支援我寫出更多好文章,謝謝!
打賞作者
打賞支援我寫出更多好文章,謝謝!
任選一種支付方式