Some suggestions and guidelines on JavaScript API design, including javascriptapi

Source: Internet
Author: User

Some suggestions and guidelines on JavaScript API design, including javascriptapi

Design is a common concept. It can generally be understood as a Plan or Framework to be prepared in advance. In the Oxford English Dictionary, design is a main thread that binds art, system, hardware, or more. Software design, especially the sub-class API design, is the same. However, API design often pays little attention to software development, because the importance of writing code for other programmers should be focused on application uidesign and end user experience.

However, API design, as a public interface provided by our own library, can show some features and functions of our library to the developers who call our code. Therefore, API design is as important as uidesign. In fact, both of them provide basic methods for applications to provide better user experience. Application UI plays an important role in user UX. Application API is the developer's UX. Therefore, the application API design should be given the same level of consideration and attention as the interfaces we provide to users. Just as we focus on the functions, conciseness, and beauty of the UI, we should also evaluate the efficacy, conciseness, and code beauty of the API!

API design-the content of javascript API design presents the only challenge for 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 for API designers. However, there is no shortcut to a good API design, but it is possible to extract some design principles from some popular modern javascript libraries!

API design: The fight between angels and demons

The poor design of javascript APIs brings high costs to developers who use your APIs. Poor design will lead to a waste of time. developers who use your API will waste time trying to understand your interface, API developers may waste time dealing with increasing demands and solving users' confusions. However, when almost all apis were originally developed, they were designed to extract the same functions, facilitate calls and save time. However, poor API design may cause your database users to be confused. Can these databases really save time?

Excellent API design, on the one hand, achieves the goal of extraction and self-description. When an API is well designed, users can quickly and intuitively complete their work without having to constantly use documents or continuously access or answer websites. You can also save time for database developers by encapsulating some features that developers need to spend a lot of time developing. A good design not only saves developers time, but also makes them look smarter and responsible. Similarly, helping your users look smart and competent will make you look more awesome!

API design is especially important for javascript.

No matter what programming language or framework, API design is important. The importance of API design is higher than that of many other languages for javascript. First, as a dynamic and later-bound language, javascript does not have a compiler to implement a security net or detection unit function, so javascript cannot detect errors in your code. Linting or validation frameworks such as JSLint and JSHint can help us. The functions of these frameworks can point out some common errors in javascript, but when we use APIs, they cannot find javascript errors.

All of this depends on you. You can develop an API with good design. This API can help your users fall into the well-known "Success trap ", this means that your library is comfortable and familiar to developers. It also provides positive reinforcement and confidence to be built when developers interact with your code.


The best example of "falling into the trap of success" is jQuery's use of DOM elements through the CSS selector syntax. For example, if I want to obtain all the article elements with class names, I can use jQuery to do this:
 

$("article.blogPost").fadeIn();

The selector article. blogPost uses the same syntax as the following, which is not accidental!
 

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

JQuery's selector engine is designed to allow me and other developers to understand CSS selectors and interact with their engines. As you can imagine, if jQuery requires a new syntax for a specific purpose, I will lose the speed, clarity, and efficiency.

We can get inspiration from these frameworks, such as jQuery, or other frameworks, and apply them to our design. However, it is not plagiarism to get inspiration. There is a problem of degree. If anyone who designs an API is based only on others' ideas, both good and bad will inherit it. If we apply the rules obtained from good javascript to other fields, we can develop a framework with good APIs that can be used in any situation.

Excellent Javascript APIs design tips

Although software does not have visual evaluation standards similar to painting or construction, we still tend to use adjectives like physical entities to describe software quality. For example, it is not uncommon to use "elegant" or "beautiful" to praise software. If it is reasonable to use adjectives similar to physical entities to describe software interfaces, the same principles can also be used to evaluate software design.

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

  1. Harmony
  2. Balance
  3. Symmetric
  4. Highlights

One or more instances are listed for each principle. These examples show how the popular Javascript library API design follows these principles.

Principle 1: consistency and coordination

In artistic works, consistency is an indispensable concept behind a work, or how designers make things a coherent whole. Coordination, on the other hand, is the layout of similar elements in a work, which will produce a concise feeling when considering the whole.

For API designers, these principles can be achieved by using similar and (or) Unified elements in the class library. Take Kendo UI for example, a javascript framework for creating rich web applications. Kendo UI provides a series of UI controls and tools, which can be initialized through a simple syntax. For example, if I want to create a TreeView from an unordered list, I only need to call the following method:
 

$("ul.tree").kendoTreeView({ /* Configuration goes here */ });

Kendo UI tree component

If I want to create a panel PanelBar through a list, I just need to change it to a different call method.
 

$("ul.panel").kendoPanelBar({ /* Configuration goes here */ });

Kendo UI panel component

The Kendo UI uses consistent kendoX syntax for all components to facilitate overall coordination. More importantly, this design relies on jQuery objects to encapsulate a unified layer for DOM elements, so that all developers are familiar with jQuery. Millions of developers use similar "tuyu" (jQuery syntax), and Kendo UI can be used smoothly across libraries.

Another example of coordination is the Backbone [object]. extend syntax to create objects, inherit and extend the functions of the Backbone Models, Views, Collections and Routers. You can use the following code to create a Backbone Model with full support for Backbone, or customize the functions you need:
 

var Book = Backbone.Model.extend({ initialize: function() { ... }, author: function() { ... }, pubDate: function() { ... },});

The purpose of unification and coordination is to make API beginners feel familiar and comfortable. Although the functions are different, but the syntax is the same or similar, so that the API becomes familiar, greatly reducing the burden on developers to use new tools.

Principle 2: Balance

The next principle is balance. When an organizational element is used, it does not make a part too heavyweight to cover other parts. In works of art, the balance is the visual weight. Even if asymmetric, the work can still feel the balance under Asymmetric, because it follows a certain pattern. The balance of API design in the context refers to the visual weight and predictability of the Code (visible function ).

Balanced APIs make people think that their components belong to each other. They perform the same action or accomplish a goal in a complementary manner. Through expansion, APIs can also feel balanced, allowing developers to easily predict and use other APIs. For example, in the property test of Modernizr, their balance is in two aspects. a) the attribute name corresponds to the HTML5 and CSS terms and API names. B) The true or false values are returned for each property test.
 

// All of these properties will be 'true' or 'false' for a given browser Modernizr.geolocation Modernizr.localstorage Modernizr.webworkers Modernizr.canvas Modernizr.borderradius Modernizr.boxshadow Modernizr.flexbox

 

Access a single attribute to tell developers about the relevant attributes, so that they can access every other attribute through it. The strength of a high-quality API lies in its simplicity. Balance also ensures that the code that I write to interact with Modernizr has the same visual weighting for each read/write operation. How to Use and Access APIs seems the same as I do, regardless of my practice. On the other hand, if Modernizr adds a polyfill Canvas API, not only the visual weighting of the class library is affected by the new API, but also the scope and usage of Modernizr will be greatly expanded, in addition, I was limited in predictability when interacting with APIs.

Another way to achieve a balance is to obtain predictable results by familiarizing developers with the concept. A typical example is jQuery's selector syntax (jquery selector syntax), 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

Jquery avoids the new selector syntax by using a familiar concept and ing it to its own class library, colleagues also created a mechanism for new users to quickly apply class libraries to production through a predictable API ..

Principle 3: Adequacy

The following principle is commensurate. It is used to measure the size and quantity of elements in a work. A good API is not so much a small api, but its adequacy is relative to its purpose. A commensurate API matches its surface with its capability range.

For example, Moment. js, a popular date conversion and formatting class library, can regard it as commensurate, because its API surface is compact and it exactly matches the purpose of the class library. Moment. js is used to process dates. Its API provides convenient functions to process javascript Date objects:
 

moment().format('dddd');moment().startOf('hour').fromNow();

For a targeted class library like Moment. js, it is very important to keep API focus and simplicity. For larger and broader class libraries, the size of the API should reflect the capabilities of the class library.


Taking Underscore as an example, as a library for multiple functions, it provides a large number of convenient functions that are designed to help developers process javascript collections, arrays, functions, and objects. Its API volume far exceeds that of libraries such as Moment. js, but 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 arrays, and the last one is to process strings.
 

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

When a database grows, the challenge of maintaining the proportion becomes more severe. To ensure that every function and function added to the database can enhance the database, more investment is required. For a large library like kendo UI, the purpose of scalability does not mean that we need to add each feature to the library. For a library as big as kendo, function objects and features should prove their value before they can be included in the library. For example, Kendo UI's 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 like a common data source, and it feels beyond the basic purpose of the database. However, today's website decoration requires the support of dynamic data. The introduction of data sources allows the Kendo UI to use a stable and comfortable paradigm to address remote data throughout the database.
 

Turning an API into a real javascript spam drawer is dangerous for a library extension, but it is not the only danger for the library. Dropping an API that does not allow you to grow along with the library, or limiting the size of your library for some human reasons is also dangerous!

One of the best examples of API growth without processing is jQuery's jQuery or $ function. Like me, thousands of developers like jQurey, but its portal methods are messy. From DOM selection to containing DOM elements in jQuery objects, this method provides more than 11 independent overload selection methods.

In most cases, some features that are not very relevant are forced into the same API. Globally, jQuery is a large library and can be considered reasonable. On the other hand, when we try to stick a function into a single interface without considering the library proportion, jQuery can also implement this function.

If you find that you are inserting an unrelated feature into an existing method, or are trying to rationalize the addition of a function that is not suitable for the API, the change you need to make is to loosen the belt and let the database breathe. When your users call a new function that can describe the name themselves, it will save more time and will not burden another existing method.

Principle 4: Stress

In works of art, emphasis is placed on the use of comparison to make one aspect of the work stand out and form a focus. In many APIs, the focus may be the anchor of the main method of a channel or class library. For another emphasis example, you can refer to the "Link" method or fluent API. It highlights the Center Object of the class library by adding emphasis. Jquery tends to emphasize this object from many functional demonstrations:

$('ul.first').find('.overdue') .css('background-color','red') .end() .find('.due-soon') .css('background-color', 'yellow');

Another example of the emphasis on many modern class libraries is Scalability: the part that the class library Creator does not provide will provide you with a tool that you can perform on your own.

For a typical example, you can refer to jQuery's 'sfn (pronounced "effin") namespace. General extension points can be completed through countless plug-ins and supplemented 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 scalability is the Backbone's "extend" function, which we have seen in this article:

var DocumentRow = Backbone.View.extend({ tagName: "li", className: "row", events: {  "click .icon": "open",  "click .button.edit": "openEditDialog" }, render: function() { ... }});

Scalability is an important aspect of stress because it makes us aware of the fact that existing class libraries do not mean everything is perfect, and we are also encouraged to expand the appropriate class libraries. When class libraries support extension, they not only enable new usage, but also benefit countless developers from general usage. 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 ". Without class library extensions like Backbone, class libraries such as Marionette will become very complex and impossible to implement.

API design: not only for database code writers

If you are not a JavaScript library writer, but a JavaScript application developer or library implementer, you may think that the principles in this article do not apply to you. After all, when we hear "API", most people often think of third-party libraries, just like my example in this article.

The truth is that, as defined in API, it is nothing more than an interface that provides isolation functions for others' use. Now, let me emphasize a very important point in an old saying: Writing modular JS code is for practicality, and the number of times it is used is not important.


As the class library referenced in this article, you can expose your javascript code to others. Even if the user of your code is a small part or internal team-or even you build your own private class library-you don't have to consider the API design principles and these in this article as the author of a public class library implementation of Principles. The benefit of using API design is that it is designed like millions of users even if it is only for one user.

Because the API design represents the user experience for developers, it is just as important as the UI design for end users. Just as we can develop a good UI by learning some principles and referring to some good or bad examples, we can also learn a better API design in the same way. The four principles mentioned in the application text, as well as other principles you have discovered, can help you build excellent APIs and give users a good experience.

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.