JavaScriptAPI design principles-1565783227

Source: Internet
Author: User
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

  1. // Common API call method: change the color and add event listening
  2. Var elem = document. getElementById ("foobar ");
  3. Elem. style. background = "red ";
  4. Elem. style. color = "green ";
  5. Elem. addEventListener ('click', function (event ){
  6. Alert ("hello world! ");
  7. }, True );
  8. // (Hypothetical) method chain API
  9. DOMHelper. getElementById ('foobar ')
  10. . SetStyle ("background", "red ")
  11. . SetStyle ("color", "green ")
  12. . AddEvent ("click", function (event ){
  13. Alert ("hello world ");
  14. });

The setting and retrieval operations can be combined into one. The more methods, the more difficult the document may be to write.

  1. Var $ elem = jQuery ("# foobar ");
  2. // Setter
  3. $ Elem. setCss ("background", "green ");
  4. // Getter
  5. $ Elem. getCss ("color") = "red ";
  6. // Getter and setter are combined into one
  7. $Elem.css ("background", "green ");
  8. $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:

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

This method can accept a JSON object:

  1. JQuery ("# some-selector" ).css ({
  2. "Background": "red ",
  3. "Color": "white ",
  4. "Font-weight": "bold ",
  5. "Padding": 10
  6. });
  7. // Bind an event by passing a map ing
  8. JQuery ("# some-selector"). on ({
  9. "Click": myClickHandler,
  10. "Keyup": myKeyupHandler,
  11. "Change": myChangeHandler
  12. });
  13. // Bind the same handler for multiple events
  14. 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.

  1. // Original code
  2. DateInterval. prototype. days = function (start, end ){
  3. Return Math. floor (end-start)/86400000 );
  4. };
  5. // Modified code
  6. DateInterval. prototype. days = function (start, end ){
  7. If (! (Start instanceof Date )){
  8. Start = new Date (start );
  9. }
  10. If (! (End instanceof Date )){
  11. End = new Date (end );
  12. }
  13. Return Math. floor (end. getTime ()-start. getTime ()/86400000 );
  14. };

With a short 6 lines of code, our method is powerful enough to receiveDateObject, 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:

  1. Function castaway (some_string, some_integer, some_boolean ){
  2. Some_string + = "";
  3. Some_integer + = 0; // parseInt (some_integer, 10) more secure
  4. Some_boolean = !! Some_boolean;
  5. }

Process undefined

To make your API more robust, You need to identify whether it is trueundefinedThe value is passed in and can be checked.argumentsObject:

  1. Function testUndefined (expecting, someArgument ){
  2. If (someArgument === undefined ){
  3. Console. log ("someArgument is undefined ");
  4. }
  5. If (arguments. length> 1 ){
  6. Console. log ("however, it is actually passed in ");
  7. }
  8. }
  9. TestUndefined ("foo ");
  10. // Result: someArgument is undefined.
  11. TestUndefined ("foo", undefined );
  12. // Result: someArgument is undefined, but it is actually passed in.

Name Parameters

  1. Event. initMouseEvent (
  2. "Click", true, true, window,
  3. 123,101,202,101,202,
  4. True, false,
  5. 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.

  1. Event. initMouseEvent (
  2. Type = "click ",
  3. CanBubble = true,
  4. Cancelable = true,
  5. View = window,
  6. Detail = 123,
  7. Screenx= 101,
  8. ScreenY = 202,
  9. Clientx= 101,
  10. ClientY = 202,
  11. CtrlKey = true,
  12. AltKey = false,
  13. ShiftKey = false,
  14. MetaKey = false,
  15. Button = 1,
  16. 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:

  1. Function nightmare (accepts, async, beforeSend, cache, complete,/*, and other 28 parameters */){
  2. If (accepts = "text "){
  3. // Prepare to receive plain text
  4. }
  5. }
  6. Function dream (options ){
  7. Options = options | {};
  8. If (options. accepts = "text "){
  9. // Prepare to receive plain text
  10. }
  11. }

It is simpler to call:

  1. Nightmare ("text", true, undefined, false, undefined,/*, and other 28 parameters */);
  2. Dream ({
  3. Accepts: "text ",
  4. Async: true,
  5. Cache: false
  6. });

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.

  1. Var default_options = {
  2. Accepts: "text ",
  3. Async: true,
  4. BeforeSend: null,
  5. Cache: false,
  6. Complete: null,
  7. //...
  8. };
  9. Function dream (options ){
  10. Var o = jQuery. extend ({}, default_options, options || {});
  11. Console. log (o. accepts );
  12. }
  13. Dream ({async: false });
  14. // 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:

  1. // JQuery allows this write.
  2. $ (Document. body). on ('click ',{});
  3. // An error is reported when you click
  4. // TypeError: (p. event. special [l. origType] | |{}). handle | l. handler). apply is not a function
  5. // 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:

  1. If (Object. prototype. toString. call (callback )! = '[Object Function]') {// view remarks
  2. Throw new TypeError ("callback is not a function! ");
  3. }
  4. 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.

  1. // All these attributes return 'true' or 'false'
  2. Modernizr. geolocation
  3. Modernizr. localstorage
  4. Modernizr. webworkers
  5. Modernizr. canvas
  6. Modernizr. borderradius
  7. Modernizr. boxshadow
  8. 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.

  1. $ ("# Grid") // Selects by ID
  2. $ ("Ul. nav> li") // All LIs for the UL with class "nav"
  3. $ ("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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.