Some suggestions and guidelines on JavaScript API design-Basic knowledge

Source: Internet
Author: User
Tags extend

Design is a common concept that is generally understood to form a plan or framework beforehand for something that is about to be done. (Oxford English Dictionary), design is a kind of art, system, hardware or more things to weave the main line. Software design, especially as a secondary class of software design API design, is the same. But API design often pays little attention to software development, because the importance of writing code for other programmers is secondary to the application of UI design and end user experience.

But API design, as the public interface provided in our own library, can show some of the features and functionality of our library to the developers calling our code, so API design is as important as UI design. In fact, both are basic ways for the application to provide a better user experience. Application UI is an important place in user UX, and application APIs are UX for developers. Therefore, the application API design should be given the same level of consideration and attention as the interface we provide to the user. Just as we focus on the effectiveness of the UI, simplicity and beauty, we should also evaluate the effectiveness of the API, simplicity and the elegance of the code!

API design--javascript API design content that presents the only challenge to all developers, whether or not you are developing a public library or an internal library. The dynamic nature of JavaScript, the anonymity of library users and the ambiguity of requirements present a daunting challenge to API designers. However, there is no shortcut to a good API design, but it is possible to extract some design guidelines from some of the most popular JavaScript libraries in the modern age.

API design: The battle between Angels and demons

The poor design of the JavaScript API will bring high costs to developers who use your API. Poor design can lead to waste, and developers who use your APIs waste time trying to figure out what your interface is, while API developers waste time dealing with growing demands and solving user confusion. However, almost all APIs were developed in order to be able to extract the same function, easy to invoke and save time. But poorly designed APIs can make your library users and you wonder, do these libraries really save time?

Excellent API design, on the one hand, the completion of the extraction target, but also achieve the self description. When an API is well designed, users can perform their work quickly and intuitively, without the need to constantly use documents or continuous access support or answer Web sites. You can also save time for library developers by encapsulating some of the features that developers need to spend a lot of time developing. Good design not only saves developers time, but also makes them look smarter and more responsible. Also help your users look smart and able to make you look even better!

API design is particularly important for JavaScript

Regardless of the programming language or framework, API design is important, and the importance of API design is higher for JavaScript than in many other languages. First, as a dynamic and late-bound language, JavaScript does not have a compiler to implement a safety net or detection unit function, so JavaScript cannot detect errors in your code. Linting or inspection frameworks such as JSLint and Jshint can help us. The capabilities of these frameworks can point to some common bugs in JavaScript, but when we use APIs, they can't find JavaScript bugs.

It all depends on you, you can develop a good design API, this API can help your users fall into the proverbial "success hole", which means that your library is comfortable and familiar to developers, while also providing positive reinforcement and confidence when developers and your code interact.


The best example of "falling into the pit of success" is jquery's use of CSS selector syntax to get DOM elements. For example, if I wanted to get all the article elements with a class name, I could use jquery to do this:

$ ("Article.blogpost"). FadeIn ();

Selector Article.blogpost and below show the use of the exact same syntax, which is by no means accidental!

article.blogpost {
 border-radius:10px;
 Background-color:salmon;
 box-shadow:0px 0px 10px 2px #ccc;
}

The jquery selector engine was designed to allow me and other developers to interact with my understanding of the CSS selector and its engine. As a result, if jquery needed me to use a new syntax for a particular purpose, I would lose speed, apparent and efficient.

We can get inspiration from these frameworks, such as jquery, or other frameworks, and apply these inspirations to our design. However, inspiration is not plagiarism, there is a degree of problem, anyone who has designed the API if it is only based on other people's ideas, whether good or bad, he will inherit. If we apply the guidelines obtained in good JavaScript to other areas, we can develop frameworks with good APIs that can be used in any case.

Excellent JavaScript APIs design tips

Although the software does not have a visual evaluation standard similar to painting or architecture, we still tend to use adjectives like physical entities to describe software quality. For example, it is not uncommon to use "elegant" and "beautiful" to compliment software. If it is reasonable to describe software interfaces with adjectives similar to physical entities, then of course you can use the same principles to evaluate software design.

In this section, four popular design principles from the Art field are extended to the API design:

    1. Harmonious and consistent
    2. Balance
    3. Symmetric
    4. Focus prominently

For each principle, one or more instances are listed, showing how the popular JavaScript Library API design follows these principles.

Principle 1: Consistency & coordination

In works of art, consistency is an indispensable idea behind a work, or how a designer makes a coherent whole of something. Coordination, on the other hand, is the layout of a similar element in a work, which creates a concise feeling when considering the whole.

For the designer of the API, these principles can be implemented by using similar and/or unified elements in the class library. Take the Kendo UI for example, a JavaScript framework for creating rich Web applications. The Kendo UI provides a series of UI controls and tools that can be initialized with a simple syntax. For example, if I want to create a tree control (TreeView) from an unordered list, I just call the following methods:

$ ("Ul.tree"). Kendotreeview ({/* Configuration goes Here/});

Kendo UI Tree Component

If I want to create a panel panelbar from a list, I just need to change it slightly to a different calling method.

$ ("Ul.panel"). Kendopanelbar ({/* Configuration goes Here/});

Kendo UI Panel Component

The kendo UI uses a consistent kendox syntax for all components to facilitate overall coordination. More importantly, such designs rely on jquery objects to encapsulate a unified layer of DOM elements, making the design beneficial to all familiar jquery developers. Millions of developers use a similar "vernacular" (jquery syntax), the Kendo UI can be successfully used across libraries.

Another coordinated case is the backbone [Object].extend syntax Creation object, which inherits and extends backbone's models,views,collections and routers functions. You can create a backbone Model with the following code, complete support with backbone, or customize the features I need:

var book = Backbone.Model.extend ({
 initialize:function () {...},
 author:function () {...},
 pubdate:functi On () {...},
});

The goal of unity and coordination is to make the API novice feel familiar and comfortable. The API becomes familiar with the same or similar syntax, although the functionality is different, greatly reducing the burden on developers to use new tools.

Principle 2: Balance

The next principle is balance, the elements of the organization will not let a certain part too heavy and cover the other parts, the use of unstable. In works of art, balance is the visual weight. Even if it is asymmetrical, the work can still feel asymmetrical equilibrium, because it follows a pattern. The balance of API design in context, I refer specifically to the visual weight and predictability of the code (see function).

The balanced API makes people feel that their components belong to each other, that they act the same way, or that they accomplish a goal in a complementary manner. By scaling, APIs can also feel balanced, allowing developers to simply predict other APIs and use them. such as Modernizr property tests, their balance in two aspects, a the attribute name corresponds to HTML5 and CSS terms and API name, b) Each property test returns a value of TRUE or false uniformly.

All of these properties is ' true ' or ' false ' for a given browser
 modernizr.geolocation
 modernizr.localstor Age
 modernizr.webworkers
 modernizr.canvas
 modernizr.borderradius
 Modernizr.boxshadow
 Modernizr.flexbox

Accessing a single attribute to tell the developer what to learn about the attributes to access each of the other attributes, the strength of a high quality API is its simplicity. The balance also ensures that my code for writing and MODERNIZR interaction has the same visual weighting every time it reads and writes. How do I look and feel when I use and access the API, regardless of my routine. On the other hand, if Modernizr adds a Polyfill canvas API, not only is the visual weighting of the class library affected by the new API, the scope and usefulness of MODERNIZR will be greatly expanded, and the predictability of my interaction with the API is limited.

Another way to achieve a balance is to get predictable results by relying on developers ' familiarity with concepts. A typical example is the jquery ' s selector syntax (the syntax of the jquery selector), which maps the css1-3 selector to its own 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

By using a familiar concept and mapping to its own class library, jquery avoids the new selector syntax, and colleagues also create a mechanism for new users to quickly apply a class library to production through a predictable API.

Principle 3: Proportionality

The next principle is proportionality, which is used to measure the size and quantity of elements in a work. A good API is a small API, and proportionality is relative to the size of the application. A proportionate API to its API surface and its ability to range to match.

For example, Moment.js, a popular date conversion and Format class library, can consider it to be proportionate because its API surface is compact and clearly matches the purpose of the class library. Moment.js is used to process dates, and its APIs provide a handy feature for handling JavaScript date objects:

Moment (). Format (' dddd ');
Moment (). StartOf (' Hour '). Fromnow ();

For a targeted class library, like Moment.js, it's important to keep the API focused and simple. For larger and broader class libraries, the size of the API should reflect the capabilities of the class library itself.


For underscore, a library of multiple uses, it offers a number of handy functions that are designed to help developers deal with JavaScript collections, arrays, functions, and objects. Its API is far more than a library like Moment.js, but the underscore is proportional, because each function in the library has its own purpose. Consider the following example, the first two examples use underscore to process the array, and the last one to handle the string.

_.each (["Todd", "Burke", "Derick"], function (name) {
 alert (name);
});
 
_.map ([1, 2, 3], function (num) {return
 num * 3;
});
 
_.isnumber ("ten"); False

As a library grows, the challenge of maintaining proportions becomes more severe. To ensure that each function and function added to the library strengthens the library's purpose, more consideration is required. For a large library like the kendo UI, the purpose of extensibility does not mean that we need to add each feature to the library. For a library as large as kendo, functional objects and attributes should prove their value to be included in the library. For example, Kendo UI ' JavaScript is based on DataSource, which can be used to query and process remote data.

var dataSource = new Kendo.data.DataSource ({
 transport: {
  read: {
   URL: "http://search.twitter.com/ Search.json ",
    dataType:" Jsonp ",
    data: {q:" API Design "}
   }
  ,
 schema: {data:" Results "}
   });

At first glance, it seems to be a habitual source of data, feeling beyond the basic purpose of the library itself. However, today's site decoration requires dynamic Data support. The introduction of a data source allows the kendo UI to use a stable and comfortable paradigm to resolve remote data throughout the library.

Turning an API into a veritable JavaScript trash drawer is dangerous for an extension of a library, but it's not the only danger for libraries. It's also dangerous to fall into the trap of not letting your API accompany the library, or limiting the size of your library for some man-made reasons!

The best example of not handling API growth is jquery or $ function. Like me, there are thousands of developers who love Jqurey, but its portal approach is a bit messy, from DOM selection to the inclusion of DOM elements in jquery objects, which provides more than 11 independent overload options.

For the most part, some features that are not very relevant are shoved into the same API. On the whole, jquery is a large library and can be considered a reasonable proportion of the library. On the other hand, when we try to cram a feature into a single interface and do not consider the library scale, the jquery method can also implement this functionality.

If you find that you are stuffing an irrelevant feature into an existing method, or trying to rationalize the addition of a function that doesn't fit the API, the change you need to make is to loosen the belt and let the library breathe. Your users will save more time by calling a new function that can be self-describing, and will not add a burden to another already existing method.

Principle 4: Emphasis on sex

In the works of art, the emphasis is on using contrast to make one aspect of the work stand out and form a focal point. In many APIs, the focus may be the anchor point of a channel or the main method of a class library. Another example of emphasis can refer to the "link" approach or the fluent API, which highlights the Class Library center object by adding an emphasis effect. jquery tends to emphasize this object from a number of feature demos:

$ (' Ul.first '). Find ('. Overdue ')
 . css (' background-color ', ' red '). End
 ()
 . Find ('. Due-soon ').
 css (' Background-color ', ' yellow ');

For many modern class libraries, another example of emphasis is scalability: the part that the class Library creator does not provide provides you with a tool that you can do with your own extensions.

A typical example can refer to the jquery ' SFN (pronounced "effin") namespace, where general extension points can be accomplished through countless plug-ins and supplemental class libraries:

(function ($) {
 $.fn.kittehfy = function () {return
  This.each (function (idx, EL) {    
   var width = el.width,
    Height = el.height;
   var src= "http://placekitten.com/";
   el.src= src + width + "/" + height;
  });
 }
(JQuery);

Another example of extensibility is the backbone "extend" function, which we've seen in this article:

var Documentrow = Backbone.View.extend ({
 tagName: "Li",
 className: "Row",
 events: {
  "click. Icon" : "Open",
  "click. Button.edit": "Openeditdialog"
 },
 render:function () {...}}
);

Scalability as a matter of emphasis because it makes us aware of the fact that the existing class library does not mean that everything is perfect, but also encourages us to expand the class library that is right for you. When the class library supports extensions, they not only open up new uses, but also enable countless developers to benefit from the general purpose. One of the best examples is the Backbone.marionette framework, a class library extended to backbone, which aims to "simplify the structure of large JavaScript applications". Class libraries such as marionette will become very complex or even impossible to implement without a class library extension like backbone.

API design: Not just for library code writers

If you are not the creator of a JavaScript library, but a JavaScript application developer or library implementation, you may think that the principles in this article do not apply to you. After all, most of us tend to think of a third-party library when we hear the "API," as I did in the example in this article

The fact is that the API, as its definition says, is nothing more than an interface that provides isolation for others to take advantage of. Now, let me use an old saying to emphasize a very important point: to write modular JS code is for practical use, the number of times is not important.


As the class library referenced in this article, you can expose your JavaScript code to other people. Even if the user of your code is a small or internal team--even if you build a private class library of your own--you don't have to consider the API design principles and implementations of these principles in the same way as an author of a public class library. The advantage of using API design is that even for one user, it is designed to be like millions of users.

Because the design of the API represents a user experience for the developer, it is like the importance of UI design to end users. Just as we can develop a good UI by learning some principles and referencing some good or bad examples, we can learn better API design in the same way. The four principles mentioned in the application, as well as other principles that you discover yourself, can help you build an excellent API and give users a good experience.

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.