[Effective JavaScript Notes] Chapter 6th: Library and API Design--Personal summary

Source: Internet
Author: User
Tags naming convention object object

Objective

Again to a chapter of the summary, the contents of this chapter. is to put me from the user of a code, how to change into a code writer. How to make it easier for others to use their own code, without having to pay attention to too many useless details, without remembering the lengthy function names. How to avoid the user's understanding deviation when using the API. How to deal with some special sensitive values, how to set parameters can be better self-description, how to reduce the dependency of the API on the state, how to make the API more flexible, more conducive to user writing. The following is an introduction, the corresponding will also explain each of the corresponding want to give advice!

53rd: The agreement to maintain a consistent personal summary

Do not create a unique API, to use some of our usual vocabulary, parameters. For example, using a uniform naming convention, similar attributes set the same order of attributes.

Naming conventions

There are many kinds, such as:

    • The first letter of the construction function is capitalized. such as MyClass

    • Normal function, prototype method, variable, lowercase letter start, other words first letter capitalization. such as Comparefn,a.setvalue (), Goodname.

    • Constants and global variables, capitalized for all letters. such as pi=3.1415

    • Private prototype methods and properties, which begin with _. such as _good, _getname ()
      Like the above content is in the JS writing process of the idiomatic method, when you see the above naming, will naturally know what the meaning of the expression.

setting of parameters

For example, when we use a function in jquery, some functions pass in a parameter, which is the value operation. It is a value operation to pass in two parameters.
Such as

$(‘.a‘).css(‘width‘);$(‘.a‘).css(‘width‘,100);$(‘a‘).attr(‘href‘);$(‘a‘).attr(‘href‘,‘http://wengxuesong.cnblogs.com‘);

As can be seen from the above, these functions pass in the first parameter as a property value that can be set and obtained. The second parameter is a value to use. When we encounter a similar function, we can use it very quickly when we use it. Like what

$(‘.b‘).data(‘name‘);$(‘.b‘).data(‘name‘,‘wxs‘);

You'll soon know the meaning of the above.
And the functions used are simple words that are easy to remember and conform to the meaning of the function.
It can be seen that some of the above settings allow us to solve some of the problems mentioned in the preface.
How to make it easier for others to use their own code without having to pay attention to too many useless details without remembering lengthy function names

Tips
    • Using a consistent convention in variable naming and function signing

    • Do not deviate from the conventions that users are likely to encounter in their development platform

54th: Undefined as a "no value" personal summary

Because there are so many undefined, it is not so easy to distinguish the real meaning of the undefined when it comes to dealing with it.

Several cases of generating undefined values
    • No assignment after variable declaration

    • The function parameter does not pass in the true real argument, the value of the formal parameter

    • The value of the function's run result when the function runs without a return value or a direct return

    • The value of the property that the object does not exist

Undefined cannot be treated as a special value for function judgment because the function cannot determine whether the parameter is really passed as a undefined or as the result of an expression run. To undefined only as a "no value" to treat. If you want to handle a situation in a special way, you can use an option object as a parameter.

Optional parameters
    • Optional parameters are undefined when no value is entered. At this point the arguments.length does not count toward this parameter.

    • When an optional parameter is passed to a value of undefined. At this point the Arguments.length accountant into this parameter.

function Server(port,hostname){  if(arguments.length < 2){    hostname=‘localhost‘  }  hostname=‘‘+hostname;  return ‘http://‘+hostname+‘:‘+port;}var s1=new Server(80,‘cnblogs.com‘);//"http://cnblogs.com:80"var s2=new Server(80);//"http://localhost:80"var s3=new Server(80,undefined);//"http://undefined:80"

Using Arguments.length to judge function optional parameters results in an error. The optional parameters should be compared to the undefined to implement the functionality.

function Server(port,hostname){  if(hostname===undefined){    hostname=‘localhost‘  }  hostname=‘‘+hostname;  return ‘http://‘+hostname+‘:‘+port;}var s1=new Server(80,‘cnblogs.com‘);//"http://cnblogs.com:80"var s2=new Server(80);//"http://localhost:80"var s3=new Server(80,undefined);//"http://localhost:80"
Implicit type conversions

When an implicit type is converted to true, undefined is converted to false. But there are many more values besides undefined that can be converted to false, such as: null, "" (empty string), 0, and Nan.
When you use a truth test in a function parameter, the default value is set. If the above 0 or an empty string is a valid value, it cannot be judged by the truth.

function W(w){  this.w=w||100;}var sw=new W(0);sw.w;//100

If you pass in 0 above, you get an object that expects a width of 0.
In this case, it must be shown to determine whether the value passed in is undefined.

function W(w){  this.w=w===undefined?100:w;}var sw=new W(0);sw.w;//0

This solves the problem of how to deal with some special sensitive values.

Tips
    • Avoid using undefined to represent any value

    • Use a descriptive string value or an object that names a Boolean property instead of using undefined or null to represent a specific app flag

    • The default value for the supplied parameter should be in the way of test undefined instead of checking arguments.length

    • In a place where 0, Nan, or an empty string is a valid parameter, you should never implement a parameter default value by using a truth test.

55th: The option object that receives the keyword parameter personal summary

In summary, when a function receives many parameters, the order of the parameters cannot be changed (this is also known as positional parameters), causing some unwanted values to be passed in, and not able to handle multiple optional parameters. Like what

function aaa(a,b,c){  //b,c都是可选的}aaa(‘a‘,,‘c‘)

As above, if I b do not want to pass only want to transfer a,c also must pass in the B passed in. Or the code inside will go wrong.
The above code also memory is a challenge, the inside of each parameter should correspond to what value.
In this case, you can choose to use the option object.

Option Object

Using the Option object, the property name in the option object can be a good illustration of the role of the parameter. Option object parameter, only non-required parameters are processed. For non-required parameters, you can provide some default values.

    • If only optional parameters are included. All parameters may be omitted, and the option object includes all parameters.

    • If you have one or two required parameters, make them independent of the option object.

Use the default Value setting for the option object for each item value. All non-required parameter entry values need to be detected. This work is not good to do, need to deal with the truth test, or exclude reasonable value of the situation and so on. Doing so is more cumbersome than using positional parameters. You can use the overlay processing method of an object to abstract the processing of the object overlay and then invoke it, which makes the logic of the code clearer. Like what

function A(parent,message,opts){  opts=extend({    width:320,    height:240  });  opts=extend({    x:10,    y:10,    title:‘alert‘,    modal:false  },opts);  extend(this,opts);}

The abstract extension function is

function extend(target,source){  if(source){    for(var key in source){      var val=source[key];      if(typeof val !== ‘undefined‘){        target[key]=val;      }    }  }  return target;}

Consistency is the goal of library design, which can give the user of the API better prediction of its function and usage.
This solves the problem of how to avoid the user's understanding when using the API. How to handle some special sensitive values, how the parameters are set can be better self-explanatory.

Tips
    • Using option objects makes the API more readable and easier to remember

    • All parameters provided through the option object should be considered optional

    • Use the Extend function to abstract logic that extracts values from an option object

56th: Avoid unnecessary state of personal summary

The API is divided into two categories: stateful and stateless. A stateless API is equivalent to a pure function, and the behavior depends only on the input, regardless of the environment state in which the program is located. There are stateful methods that may return different results for the same method. Depends primarily on the state of the method in which it is located.
Stateless APIs are easier to learn and use, because all behaviors are determined by the function itself, as long as the code that queries the relevant function knows the output is correct.
Stateful APIs are in different states and may produce different results. Causes extra information to be memorized and used. The change in state also often leads to a higher degree of coupling of the code. Stateless APIs can make your code more modular and avoid coupling with other code.
The stateless API is better when designing the API.

Tips
    • Use stateless APIs as much as you can

    • If the API is stateful, indicate which states are associated with each operation

57th: Design flexible interfaces using structural types personal Summary

struct type (duck type): Any object that has the expected structure belongs to that type. This is similar to the strongly typed object-oriented language interface, that is, interface-oriented programming.
The structure type can be beneficial to unit testing and can easily implement a test data structure.
struct types can also decouple code from each other, and the code relies only on the structure type.
In implementing the code, you do not have to pipe the final implementation details of the structure type, as long as the corresponding methods and properties are provided, then the program can run normally.

Tips
    • Design flexible object interfaces using struct types

    • Structure interfaces are more flexible and lightweight, so you should avoid using inheritance

    • For unit testing, the use of mock objects, the alternative implementation of interfaces, to provide a reusable behavior

58th: Distinguish between array objects and class array objects personal summary separating array objects

Array objects and class array objects can be distinguished directly by using type judgments.

var a=[];var b={0:1,length:1};var toString=({}).toString;toString.call(a);//"[object Array]"toString.call(b);//"[object Object]"

So at a glance. But this is disputed with the concept of JS's flexible class array object, because any object can be treated as an array, as long as it follows the correct interface. The last one uses a structure type to design a flexible interface. Flexible structure as long as a data conforms to the corresponding interface, it can be regarded as the correct data.

Overload

Overloading two types means there must be a way to differentiate between two different situations. The API cannot be overloaded if there are overlapping areas for both cases.
The API should never overload types that overlap with other types.

Array.isarray function

This function tests whether a value is an array, regardless of the stereotype inheritance.

var a={};var b=[];var c=10;Array.isArray(a);//falseArray.isArray(b);//trueArray.isArray(c);//false

You can directly distinguish between arrays and arrays of classes.

Class array conversions to arrays
var slice=[].slice;var b={0:10,1:‘good‘,length:2};slice.call(b);//[10,‘good‘]

If the API's incoming parameters have special requirements, you need to note in the document, the API overload must also be noted, the parameters of different conditions.

Tips
    • Never overload a struct type that has overlapping other types

    • When you overload a struct type with another type, test other types first

    • Receive true arrays instead of class array objects when other object types are overloaded

    • Document callout Whether your API receives a true array or class array value

    • Test a true array using the Array.isarray method provided by ES5

59th: Avoid excessive forced conversions personal summary overloads and casts

Overloading is based on the judgment of the type, and the coercion causes the parameter type information to be lost, resulting in a different result than expected.
You should avoid casting when you use parameter types as an overloaded basis.
Overloading is done by enforcing the design of the API by forcing the type of the parameter so that the code is more cautious.

Defensive programming

Protect against potential errors with additional checks. It is impossible to resist all errors. In addition to the basic inspection tools provided in JS, you can write some concise check tool functions to assist the development.
Additional code can affect the performance of the program or catch errors earlier. Look at the specifics to use defensive programming.

Tips
    • Avoid the mixing of casts and overloads

    • Consider defensive monitoring of unexpected inputs

60th: Support Method Chain Personal Summary

JS in-band method chaining calls, such as the Replace method of a string

function escapeBasicHTML(str){    return str.replace(/&/g,"&amp;")              .replace(/< /g,"&lt;")              .replace(/>/g,"&gt;")              .replace(/"/g,"&quot;")              .replace(/‘/g,"&apos;");}

Array method

var users=records.map(function(record){    return record.username;}).filter(function(username){    return !!username;}).map(function(username){    return username.toLowerCase();});

These can be written in a traditional way, saving each return value to an intermediate variable.
The key to implementing a method chain is to return the object of the next method each time.
In a stateless API, you can return a new object, and the chain gets a natural result. Like the Replace method above, a new string object is returned.
Stateful APIs are also worth using, when a method chain is called a fluent type. This is a good example of how to do this in jquery.

$(‘body‘).html(‘good‘).addClass(‘y‘);

The writing style of the method chain requires the code to be processed to support (returning the object itself). The code of the method chain can be rewritten as a traditional style.

Tips
    • Using a method chain to connect stateless operations

    • Support for method chains by returning new objects in a stateless method

    • Supports the method chain by returning this in a stateful method

Summarize

Throughout this chapter, guidance is given from a higher level than writing specific code. All the way up and down, the document is important. There are special requirements and the use of different to the document description.

    • When processing API interface naming, keep naming conventions consistent and not deviate from user habits.

    • Special objects should not be handled easily when handling undefined.

    • Parameters using option parameters are more descriptive and easier to remember and use.

    • Design a stateless API interface that is easier to modularize and use.

    • The API is more flexible for structural type programming.

    • Function overloading be aware of different situations and cannot have overlapping areas.

    • Coercion destroys overloads that depend on type judgment.

    • Supports the method chain, which makes the code more fluid to write.

In the penultimate chapter, there is one more chapter to be finished. Although the content of this chapter is not much, I seem to be struggling with these chapters because I can't find the focus. How much of the code directly determines the degree of understanding of the article, this chapter can be written in some code back and then look again and again, after mastering the ability to become their own.

[Effective JavaScript Notes] Chapter 6th: Library and API Design--Personal summary

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.