API design principles for JavaScript

Source: Internet
Author: User

Objective

This blog post comes from a company-wide front-end share that discusses the principles of designing interfaces in a number of ways, with a total of seven chunks. A series of lessons to be summed up by the brine boil itself. Also refer to some articles, the address will be posted in the back. It is difficult to do a detailed enrichment, if there are good suggestions or the wrong place, but also hope to enlighten treatise.

First, the flow of the interface

The good interface is smooth and easy to understand, he mainly embodies the following aspects:

1. Simple

To manipulate the CSS properties of an element, here is the native method:

Document.queryselectorall (' #id '). Style.color = ' red ';

After encapsulation

function A (selector, color) {  document.queryselectorall (' #id '). Style.color = Color}a (' #a ', ' red ');

From a dozens of-letter long line to a simple function call, the API is easy to use

2. Accessibility

A (' #a ', ' red ') is a good function that helps us to change an element in a simple and practical way, but the question is, if the person who first uses the modifier will be confused, what function a function is, and no one tells him. Development interface It is necessary to know that people are lazy, from the color assignment of this function, although less code, but increased the cost of memory. Each time you do this, you need to have a mapping relationship. A---->color. If it's a few simple, but usually a set of frameworks have dozens of or even hundreds of APIs, the increase in mapping costs will cause the programmer brother collapse. What we need is to make the interface meaningful, so let's rewrite the A function:

function Letsomeelementchangecolor (selector, color) {  Document.queryselectorall (selector, color);}

Letsomeelementchangecolor is given a linguistic meaning relative to a, and anyone will know what it means.

3. Reduce memory costs

That's what we just did. It's too long, letsomeelementchangecolor. Although it reduces the cost of mapping, it increases the cost of memory. You know, everyone, including genius, doesn't like to be words. Native Get Dom API also has this problem document.getelementsbyclassname; document.getelementsbyname; Document.queryselectorall; These APIs give the impression that the word is too long, although the meaning he gives is clear, but it is based on the sacrifice of simplicity. So we rewrite the previous function again.

Reduce the function name under the condition that the meaning is not large. Make it easy to read easy to remember easy to use;

4. Can be extended

Extension refers to the use of functions like flowing water in the order in which they are written to form the chain of execution:

document.getElementById (' id '). style.color = ' Red ';d Ocument.getelementbyid (' id '). style.fontsize = ' 12px '; document.getElementById (' id '). style.backgourdcolor = ' Pink ';

Before using our previous method is to encapsulate again two function setfontsize, SetBackgroundColor; Then execute them setcolor (' id ', ' red '); Setfontsiez (' id ', ' 12px '); setbackgroundcolor (' id ', ' pink '); Obviously, this kind of practice does not have the lazy state, the ID element needs to regain each time, affects the performance, the failure, each time needs to add the new method fails each time to call these methods, or fails. Let's rewrite it as a function that can be extended to first encapsulate the Get ID method into an object, and then return the object in every method of the object:

function GetElement (selector) {  This.style = Document.queryselecotrall (selector). style;} GetElement.prototype.color = function (color) {  This.style.color = color;  return this;} GetElement.prototype.background = function (bg) {  this.style.backgroundColor = color;  return this;} GetElement.prototype.fontSize = function (size) {  this.style.fontSize = size;  return this;} Call var el = new GetElement (' #id ') el.color (' Red '). Background (' Pink '). FontSize (' 12px ');

Simple, fluid, easy to read, we'll talk about how to optimize in the parameters. So, everyone prefers to use jquery's API, although a $ symbol does not represent any practical significance, but simple symbols are beneficial to our use. It embodies the above principles, simple, easy to read, easy to remember, chain-style, multi-parameter processing.

Nightware:

document.getElementById (' id '). style.color = ' Red ';d Ocument.getelementbyid (' id '). style.fontsize = ' 12px '; document.getElementById (' id '). style.backgourdcolor = ' Pink ';

Dream:

$ (' id '). css ({color: ' Red ', fontSize: ' 12px ', BackgroundColor: ' Pink '})
Second, consistency

1. Consistency of the interface

The relevant interface maintains a consistent style, and a full set of APIs that convey a sense of familiarity and comfort will greatly reduce the developer's adaptability to new tools. Name this: short, self-describing, and most importantly, consistency "in the computer science community there are only two headaches: cache invalidation and naming problems"-phil Karlton Choose a phrase you like and then use it consistently. Choose a style, and then keep that style.

Nightware:

Setcolor,letbackgroundchangefontsizemakedisplay

Dream

Setcolor;setbackground;setfontsizeset .....

Try to keep the code style and naming style so that people read your code as if they were reading an article written by the same person.

Third, the processing of parameters

1. Types of parameters

Determine the type of parameter to provide a stable guarantee for your program

We stipulate that color accepts the string type function SetColor (color) {  if (typeof color!== ' string ') return;dosomething}

2. Using JSON to transmit parameters

There are many advantages of using JSON to pass a value, it can give the parameter name, can ignore the specific position of the parameter, can give the parameter default value and so on, such as the following bad situation:

function fn (param1, Param2...............paramn)

You have to follow each parameter in order, or your method will deviate from what you expect to do, and the correct approach is the following approach.

function fn (JSON) {//Set default value for mandatory parameter   var = extend ({param: ' default ', param1: ' Default ' ...   },json)}

This function code, even if you do not pass any parameters in, he will also be expected to run. Because at the time of declaration, you will decide the default value of the parameter according to the specific business.

Iv. Scalability

One of the most important principles of software design: Never modify an interface, refer to extend it! Scalability also requires an interface with a single, multi-duty interface that is difficult to scale. Give me a chestnut:

You need to change the font and background of an element at the same time//Nightware:function set (selector, color) {  Document.queryselectroall (selector). Style.color = color;  Document.queryselectroall (selector). Style.backgroundcolor = color;} Unable to expand the function, if you need to change the size of the font again, you can only modify this function, after the function to fill the code to change the font size//dreamfunction set (selector, color) {  var el = Document.queryselectroall (selector);  El.style.color = color;  El.style.backgroundColor = color;  Return el;} You need to set the font, background color, and size function Setagain (selector, px) {  var el = set (selector, color)  el.style.fontSize = px;  Return el;}

The above is simply add color, business complex and code is not when you write, you have to read the previous code and then modify it, obviously does not conform to the open-closed principle. The modified function returns the element object so that the return value is processed again the next time it needs to be changed.

Application of 2.this

Extensibility also includes the flexible use of this and the call and apply methods:

function Saybonjour () {  alert (THIS.A)}obj.a = 1;obj.say = Saybonjour;obj.say ();//1//orsaybonjour.call| | Apply (obj);//1
V. Handling of Errors

1. Anticipating errors

You can use the type to detect typeof or Try...catch. typeof will force the detection object to not throw an error, especially useful for undefined variables.

2. Throwing errors

Most developers do not want to make mistakes and need to find their own code, the best way is to directly in the console output, tell the user what happened. We can use the output api:console.log/warn/error of the browser. You can also leave a few bridges to your program: Try...catch.

Function Error (a) {  if (typeof a!== ' string ') {    console.error (' param a must be type of string ')  }}function er Ror () {  try {    //some code excucete here maybe throw wrong   }catch (ex) {    Console.wran (ex);  }}
VI. Predictability

The predictable Flavor program interface provides robustness to ensure that your code executes smoothly, and it must take into account abnormal expectations for it. Let's look at the difference between unforeseen code and predictable code with the previous SetColor

Nighwarefunction Set (selector, color) {document.getElementById (selector). Style.color = color;} Dreamzepto.init = function (selector, context) {var dom//If Nothing given, return an empty Zepto collection If (!se lector) return Zepto.  Z ()//Optimize for string selectors else if (typeof selector = = ' string ') {selector = Selector.trim ()//if it ' s A HTML fragment, create nodes from it//Note:in both Chrome and Firefox, DOM error-//is thrown if the F Ragment doesn ' t begin with < if (selector[0] = = ' < ' && fragmentre.test (selector)) dom = Zepto.fragme NT (Selector, regexp.$1, context), selector = NULL//If There ' s a context, create a collection on that context first, a ND Select//nodes from there else if (context!== undefined) return $ (context). Find (selector)//If it ' s a CSS s    Elector, use it to select nodes. else dom = ZEPTO.QSA (document, selector)}//If a function is given, call it when the DOM was ready else If (iSfunction (selector)) return $ (document). Ready (selector)//If a Zepto collection is given, just return it else If (zepto . IsZ (selector)) return selector else {//normalize array if an array of nodes are given if (IsArray (selector)) Dom    = Compact (selector)//Wrap DOM nodes.    else if (IsObject (selector)) dom = [selector], selector = NULL//If it ' s a HTML fragment, create nodes from it  else if (fragmentre.test (selector)) dom = Zepto.fragment (Selector.trim (), regexp.$1, context), selector = NULL// If there's a context, create a collection on this context first, and select//nodes from there else if (context! =     = undefined) return $ (context). Find (selector)//And last but no least, if it's a CSS selector, use it to select nodes. else dom = ZEPTO.QSA (document, selector)}//Create a new Zepto collection from the nodes found return zepto. Z (DOM, selector)}

The above is the source of the Zepto, you can see, the author in anticipating the parameters of the input has done a lot of processing. Predictability, in fact, provides a number of entrances to the program and cannot be a logical judgment. Zepto uses a lot of right and wrong judgments, which leads to lengthy code and is not suitable for reading. In short, predictability really requires you to do more to write some parameters about the physical location. The external detection is changed to internal inspection. Yes, the use of people comfortable and happy with ease. God The most important thing is Haisen.

Vii. readability of annotations and documents

One of the best interfaces is that no documentation is required and we will use it, but often the interface is a bit more and the business is increased, and the interface will be a little laborious to use. So the interface documentation and annotations need to be written carefully. The notes follow the principle of concise, and for many years later, they also show the following:

annotation interface, in order to demonstrate PPT with function commentary () {  //If you define a literal variable, it is best not to write a comment: A: Useless variable, you can delete  var A;  Write notes in key and ambiguous places like finishing touches: After routing to the hash interface, all the data is emptied to the End Function  return go. Navigate (' hash ', function () {    data.clear ();  });}
At last

We recommend the Markdown grammar Writing API documentation, and the GitHub document writing syntax. Simple, fast, code highlighting, words not much to say

A few online editing sites are also recommended in this stew. Gentlemen can go to practice using their own.

Https://www.zybuluo.com/mdeditor

http://mahua.jser.me/

Reference Blog

Front-end headline-javascript API design principles

API design principles for JavaScript

Related Article

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.