JavaScriptAPI design principles-1565783227 Network + offline salons | mobile APP Model Innovation: give you a reason to create an APP>
Good API design: Achieve abstract goals while self-describing.
With well-designed APIs, developers can get started quickly, without having to hold manuals and documents frequently, or frequently patronize the technical support community.
Smooth interface
Method chain: easy to read and understand
- // Common API call method: change the color and add event listening
- Var elem = document. getElementById ("foobar ");
- Elem. style. background = "red ";
- Elem. style. color = "green ";
- Elem. addEventListener ('click', function (event ){
- Alert ("hello world! ");
- }, True );
-
- // (Hypothetical) method chain API
- DOMHelper. getElementById ('foobar ')
- . SetStyle ("background", "red ")
- . SetStyle ("color", "green ")
- . AddEvent ("click", function (event ){
- Alert ("hello world ");
- });
The setting and retrieval operations can be combined into one. The more methods, the more difficult the document may be to write.
- Var $ elem = jQuery ("# foobar ");
-
- // Setter
- $ Elem. setCss ("background", "green ");
- // Getter
- $ Elem. getCss ("color") = "red ";
-
- // Getter and setter are combined into one
- $Elem.css ("background", "green ");
- $Elem.css ("color") = "red ";
Consistency
The related interfaces are in the same style. If a complete set of Apis deliver a sense of familiarity and comfort, it will greatly reduce developers' adaptability to new tools.
Naming: to be short and self-describing, the most important thing is to maintain consistency.
"There are only two hard problems in computer science: cache-invalidation and naming things ."
"There are only two headaches in the computer science field: cache invalidation and naming problems"
-Phil Karlton
Select a preferred wording and continue using it. Select a style and maintain it.
Processing Parameters
You need to consider how to use the method you provided, will it be called repeatedly? Why is the call repeated? How does your API help developers reduce repeated calls?
Receiving map ing parameters, callback, or serialized attribute names not only makes your API clean, but also makes it more comfortable and efficient to use.
JQuerycss()
You can set a style for the DOM element:
- 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
- });
-
- // Bind an event by passing a map ing
- JQuery ("# some-selector"). on ({
- "Click": myClickHandler,
- "Keyup": myKeyupHandler,
- "Change": myChangeHandler
- });
-
- // Bind the same handler for multiple events
- JQuery ("# some-selector"). on ("click keyup change", myEventHandler );
Processing type
When defining a method, you need to determine what parameters it can receive. We don't know how people use our code, but we can be more farsighted and consider which parameter types are supported.
- // Original code
- DateInterval. prototype. days = function (start, end ){
- Return Math. floor (end-start)/86400000 );
- };
-
- // Modified code
- 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 a short 6 lines of code, our method is powerful enough to receiveDate
Object, numeric timestamp, and even ImageSat Sep 08 2012 15:34:35 GMT+0200 (CEST)
Such a string
If you need to ensure that the input parameter type (string, number, Boolean) can be converted as follows:
- Function castaway (some_string, some_integer, some_boolean ){
- Some_string + = "";
- Some_integer + = 0; // parseInt (some_integer, 10) more secure
- Some_boolean = !! Some_boolean;
- }
Process undefined
To make your API more robust, You need to identify whether it is trueundefined
The value is passed in and can be checked.arguments
Object:
- Function testUndefined (expecting, someArgument ){
- If (someArgument === undefined ){
- Console. log ("someArgument is undefined ");
- }
- If (arguments. length> 1 ){
- Console. log ("however, it is actually passed in ");
- }
- }
-
- TestUndefined ("foo ");
- // Result: someArgument is undefined.
- TestUndefined ("foo", undefined );
- // Result: someArgument is undefined, but it is actually passed in.
Name Parameters
- Event. initMouseEvent (
- "Click", true, true, window,
- 123,101,202,101,202,
- True, false,
- 1, null );
The Event. initMouseEvent method is simply crazy. without reading the document, who can say what each parameter means?
Give each parameter a name and assign a default value.
- 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.
JSON object for receiving Parameters
Instead of receiving a bunch of parameters, it is better to receive a JSON object:
- Function nightmare (accepts, async, beforeSend, cache, complete,/*, and other 28 parameters */){
- If (accepts = "text "){
- // Prepare to receive plain text
- }
- }
-
- Function dream (options ){
- Options = options | {};
- If (options. accepts = "text "){
- // Prepare to receive plain text
- }
- }
It is simpler to call:
- Nightmare ("text", true, undefined, false, undefined,/*, and other 28 parameters */);
-
- Dream ({
- Accepts: "text ",
- Async: true,
- Cache: false
- });
Default Value
It is recommended that the parameter have default values, which can override the default values through jQuery. extend () http://underscorejs.org/#extend) and Protoype 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"
Scalability
Callback (callbacks)
Through callback, API users can overwrite some of your code. Enable custom functions into configurable callback functions, allowing API users to easily overwrite your default code.
Once callback is received, the API must be described in the document and provide sample code.
Events)
It is best to know the name of the event interface. You can select the event name as needed to avoid the same name as the native event.
Handling error
Not all errors are useful for developers to debug code:
- // JQuery allows this write.
- $ (Document. body). on ('click ',{});
-
- // An error is reported when you click
- // TypeError: (p. event. special [l. origType] | |{}). handle | l. handler). apply is not a function
- // In jQuery. min. js on Line 3
Debugging of such errors is very painful. Don't waste the developer's time and tell them what the mistake is:
- If (Object. prototype. toString. call (callback )! = '[Object Function]') {// view remarks
- Throw new TypeError ("callback is not a function! ");
- }
- Note: typeof callback = "function" may be faulty in the old browser, and the object will be treated as a function.
Predictability
A good API is predictable, and developers can infer its usage based on the example.
The Modernizr's feature detection is an example:
A) The attribute name used completely matches the HTML5, CSS concepts, and APIs.
B) returns true or false for each individual detection.
- // All these attributes return 'true' or 'false'
- Modernizr. geolocation
- Modernizr. localstorage
- Modernizr. webworkers
- Modernizr. canvas
- Modernizr. borderradius
- Modernizr. boxshadow
- Modernizr. flexbox
Relying on the concepts that developers are already familiar with can also be used for predictable purposes.
The jQuery's selector syntax is a notable example where the CSS1-CSS3 selector can be used directly to 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
Proportional coordination
A good API is not necessarily a small API. The size of an API must be commensurate with its function.
For example, Moment. js, a well-known date parsing and formatting library, can be called a balance. Its API is concise and functional.
Libraries with specific functions such as Moment. js ensure that the API is focused and small.
Write API documentation
One of the most difficult tasks of software development is to write documents. In fact, everyone hates writing documents, but the complaints are that there is no easy-to-use document tool.
Automatic Document generation tools are as follows:
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)