Home > Article > Web Front-end > A detailed introduction to JavaScript API design principles
Some time ago, we organized and optimized our native module API (iOS and Android modules are encapsulated into JavaScript interfaces), so I studied several articles on JavaScript API design. Although they are old articles, I benefited a lot. Record it here.
Good API design: achieve abstract goals while being self-describing.
With a well-designed API, developers can get started quickly. There is no need to hold manuals and documents frequently, and there is no need to frequently visit the technical support community.
Method chain: smooth and easy to read, easier to understand
//常见的 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"); });
Set and get operations can be combined into one ;The more methods, the more difficult it may be to write the document
var $elem = jQuery("#foobar"); //setter $elem.setCss("background", "green"); //getter $elem.getCss("color") === "red"; //getter, setter 合二为一 $elem.css("background", "green"); $elem.css("color") === "red";
Relevant interfaces maintain a consistent style. If a whole set of APIs conveys a sense of familiarity and comfort, it will Greatly ease developers' adaptability to new tools.
Name this thing: it should be short, self-descriptive, and most importantly consistent
“There are only two hard problems in computer science: cache-invalidation and naming things.”
“There are only two headaches in computer science: cache invalidations and naming problems”
—Phil Karlton
Choose a phrasing you like and continue use. Choose a style and keep it that way.
You need to consider how people use the method you provide. Will it be called repeatedly? Why is it called repeatedly? How does your API help developers reduce duplicate calls?
Receive map mapping parameters, callbacks or serialized attribute names, which not only makes your API cleaner, but also makes it more comfortable and efficient to use.
jQuery’s css()
method can set styles for DOM elements:
jQuery("#some-selector") .css("background", "red") .css("color", "white") .css("font-weight", "bold") .css("padding", 10);
This method can accept a JSON object:
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);
When defining a method, you need to decide what parameters it can receive. We don't know how people use our code, but we can be more forward-looking and consider what parameter types we support.
//原来的代码 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); };
With the addition of just 6 lines of code, our method is powerful enough to accept Date
objects, numeric timestamps, and even things like Sat Sep 08 2012 15:34: 35 GMT+0200 (CEST)
Such a string
If you need to ensure the type of the incoming parameter (string, number, Boolean), you can convert it like this:
function castaway(some_string, some_integer, some_boolean) { some_string += ""; some_integer += 0; // parseInt(some_integer, 10) 更安全些 some_boolean = !!some_boolean; }
To make your API more robust, you need to identify whether the real undefined
value is passed in. You can check the arguments
object:
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 , 然而它实际是传进来的
event.initMouseEvent( "click", true, true, window, 123, 101, 202, 101, 202, true, false, false, false, 1, null);
Event.initMouseEvent This method is simply crazy. Without reading the documentation, who can tell what each parameter means?
Give each parameter a name and assign a default value. For example,
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 or Harmony has default parameter values and rest parameters.
Instead of receiving a bunch of parameters, it is better to receive a JSON object:
function nightmare(accepts, async, beforeSend, cache, complete, /* 等28个参数 */) { if (accepts === "text") { // 准备接收纯文本 } } function dream(options) { options = options || {}; if (options.accepts === "text") { // 准备接收纯文本 } }
It is also simpler to call:
nightmare("text", true, undefined, false, undefined, /* 等28个参数 */); dream({ accepts: "text", async: true, cache: false });
It is best to have a default value for the parameters. The preset default value can be overridden through jQuery.extend() http://www.php.cn/) and Protoype's Object.extend.
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"
Through callbacks, API users can overwrite a certain part of your code. Open some functions that require customization into configurable callback functions, allowing API users to easily override your default code.
Once the API interface receives callbacks, make sure to document them and provide code examples.
It is best to know the name of the event interface. You can freely choose the event name to avoid duplication of names with native events.
Not all errors are useful for developers to debug code:
// 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
Such errors are painful to debug. Don’t waste developers’ time. Tell them directly. What mistake did they make:
if (Object.prototype.toString.call(callback) !== '[object Function]') { // 看备注 throw new TypeError("callback is not a function!"); }
Note:
typeof callback === "function"
will have problems on old browsers,object
will Think of it as afunction
.
A good API is predictable and developers can infer its usage based on examples.
Modernizr's feature detection is an example:
a) It uses attribute names that completely match HTML5, CSS concepts and APIs
b) Each individual detection is consistent Returning true or false values
// 所有这些属性都返回 'true' 或 'false' Modernizr.geolocation Modernizr.localstorage Modernizr.webworkers Modernizr.canvas Modernizr.borderradius Modernizr.boxshadow Modernizr.flexbox
relies on concepts that developers are already familiar with and can be predictable.
jQuery’s selector syntax is an obvious example. CSS1-CSS3 selectors can be used directly in its DOM selector engine.
$("#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
A good API is not necessarily a small API. The size of the API must be commensurate with its function.
For example, Moment.js, a well-known date parsing and formatting library, can be called balanced. Its API is both concise and functional.
With a function-specific library like Moment.js, it’s important to keep the API focused and small.
One of the most difficult tasks in software development is writing documentation. In fact, everyone hates writing documentation. The complaint is that there is no easy-to-use documentation tool.
The following are some automatic document generation tools:
YUIDoc (requires Node.js, npm)
JsDoc Toolkit ( requires Node.js, npm)
#The most important thing is: ensure that the documentation and code are updated simultaneously.
References:
- Good API Design
- Designing Better JavaScript APIs
- Secrets of Awesome JavaScript API Design
##
The above is the detailed content of A detailed introduction to JavaScript API design principles. For more information, please follow other related articles on the PHP Chinese website!