NET + Offline Salon | Mobile app Mode innovation: give you a reason to do the app >>
Good API design: In the self-description, at the same time to achieve abstract goals.
Well-designed APIs allow developers to get started quickly, without the need to keep manuals and documentation often, or to visit the tech support community frequently.
Smooth interface
Method chain: Smooth and easy to read, easier to understand
- Common API Call methods: Change some colors, add event listener
- var elem = document.getElementById ("Foobar");
- Elem.style.background = "Red";
- Elem.style.color = "green";
- Elem.addeventlistener (' click ', Function (event) {
- Alert ("Hello world!");
- }, true);
- (conceived) method chain API
- Domhelper.getelementbyid (' foobar ')
- . SetStyle ("Background", "Red")
- . SetStyle ("Color", "green")
- . addevent ("click", Function (event) {
- Alert ("Hello World");
- });
Settings and get operations can be combined; 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, Setter merged
- $elem. CSS ("background", "green");
- $elem. CSS ("color") = = = = "Red";
Consistency
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.
Naming this thing: both short and self-describing, and most importantly, maintaining consistency
"There is only a problems in computer science:cache-invalidation and naming things."
"There are only two headaches in the computer science: Cache invalidation and naming problems"
-phil Karlton
Choose a language that you like, and then continue to use it. Choose a style, and then keep that style.
Processing parameters
You need to think about how you can use the methods you provide, and whether they will be repeated calls? Why is the call repeated? How does your API help developers reduce repetitive calls?
Receiving map map parameters, callbacks, or serialized property names not only makes your API cleaner, it's more comfortable and efficient to use.
The JQuery css()
method allows you to style the DOM elements:
- JQuery ("#some-selector")
- . CSS ("background", "Red")
- . css ("Color", "white")
- . CSS ("Font-weight", "bold")
- . css ("padding", ten);
This method can accept a JSON object:
- JQuery ("#some-selector"). CSS ({
- " Background": "Red",
- "COLOR": "White",
- " font-weight": "bold",
- "padding": ten
- });
- Bind events by passing a map map
- JQuery ("#some-selector"). On ({
- "click": Myclickhandler,
- "KeyUp": Mykeyuphandler,
- "Change": Mychangehandler
- });
- Binding the same handler function for multiple events
- JQuery ("#some-selector"). On ("Click KeyUp Change", MyEventHandler);
Processing type
When defining a method, you need to decide what parameters it can receive. We are not sure how people use our code, but can be more visionary and consider what parameter types are supported.
- The original code
- DateInterval.prototype.days = function (start, end) {
- return Math.floor ((end-start)/ 86400000);
- };
- The 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);
- };
Adding a short 6 lines of code, our approach is powerful to receive Date
objects, numeric timestamps, and even Sat Sep 08 2012 15:34:35 GMT+0200 (CEST)
strings like this
If you need to ensure that the passed parameter type (string, number, Boolean) can be converted like this:
- function Castaway (some_string, Some_integer, Some_boolean) {
- Some_string + = "";
- Some_integer + = 0; //parseint (Some_integer, 10) more secure
- Some_boolean =!! Some_boolean;
- }
Handling undefined
To make your API more robust, you need to identify whether the actual undefined
value is passed in, and you can examine the 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 was undefined, but it actually came in.
Give the parameter a name
- Event.initmouseevent (
- "Click", True, true, window,
- 123, 101, 202, 101, 202,
- true, false , False, False,
- 1, null);
Event.initmouseevent This method is simply insane, without looking at 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.
Parameter Receive JSON object
Instead of receiving a bunch of arguments, you might as well receive a JSON object:
- Function Nightmare (accepts, async, beforesend, cache, complete,/ * etc 28 Parameters */) {
- if (accepts = = = "text") {
- //Ready to receive plain text
- }
- }
- function Dream (options) {
- options = Options | | {};
- if (options.accepts = = = "text") {
- //Ready to receive plain text
- }
- }
It's also easier to call:
- Nightmare ("text", true, undefined, false, undefined,/ * etc 28 parameters */);
- Dream ({
- Accepts: "text",
- Async: True,
- Cache: false
- });
Parameter Default value
Parameters are best with default values, which can be overridden by 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)
With callbacks, the API user can overwrite a portion of your code. Open up some features that you need to customize into configurable callback functions that allow API users to easily overwrite your default code.
Once the API interfaces receive callbacks, make sure they are documented and provide code examples.
Event (events)
The event interface is best known for its name, and the event name can be chosen freely to avoid the same names as the original event.
Handling Errors
Not all errors are useful for developer debug code:
- jQuery allows this to be written
- $ (document.body). On (' click ', {});
- Click the Times wrong
- TypeError: ((P.event.special[l.origtype] | | {}). Handle | | L.handler). Apply is not a function
- In JQuery.min.js on line 3
Such errors are painful to debug, do not waste the developer's time, tell them directly what is wrong:
- if (Object.prototype.toString.call (callback)!== ' [Object Function] ') { //See note
- throw New TypeError ("Callback is not a function!");
- }
- Remark: typeof callback = = = "function" There will be a problem on the old browser, and object becomes a function.
Predictability
A good API is predictable, and the developer can infer its usage based on an example.
Modernizr ' s feature detection is an example:
A) the attribute name it uses is fully matched to HTML5, CSS concepts, and APIs
b) Each individual detection consistently returns a value of TRUE or False
- All of these properties return ' true ' or ' false '
- Modernizr.geolocation
- Modernizr.localstorage
- Modernizr.webworkers
- Modernizr.canvas
- Modernizr.borderradius
- Modernizr.boxshadow
- Modernizr.flexbox
A concept that relies on the familiarity of the developer can also achieve predictable purposes.
The jQuery ' s selector syntax is a notable example, and the CSS1-CSS3 selector can be used directly with 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,api size to match its function.
For example, Moment.js, the famous date parsing and formatted library, can be called equalization, its API is both concise and functional clear.
A library of specific features, such as moment.js, is important to ensure that the API is focused and small.
Writing API Documentation
One of the hardest tasks in software development is writing documents, in fact everyone hates to write documents, complaining that there is no good documentation tool.
Here are some document auto-generation tools:
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)
JavaScript API Design Principles