Write maintainable javascript>> note 2 (notes)

Keywords: Javascript IE Programming Java Asterisk

Annotations are the most common part of code. They are another form of document that programmers are willing to spend their time writing at last. However, for the overall maintainability of code, annotations are a very important part. Opening a file without any annotations is like a fun adventure, but if you have limited time, the task becomes torture. Added annotations appropriately. It can explain the origin and development of the code, and other developers can read any part of the code directly instead of reading it from scratch. Programming style usually does not contain conventions about the style of annotations, but the importance of annotations can not be ignored from the role of my task.

js supports two different types of annotations: single-line and multi-line annotations.

2.1 Single Line Comments
There are three ways to use a single line comment:

  • An exclusive line of comment to explain the next line of code. This line of comment always has a blank line before it, and the indentation level is consistent with the underlying code.

  • There should be at least one indentation between the end of the code and the comment. The comment (including the previous part of the code) should not exceed the maximum number of characters per line. If it exceeds, release the comment above the current line of code.

  • Large blocks of code that have been commented out (many editors can comment out multiple lines of code in batches).

Single-line comments should not appear in the form of continuous multi-line comments unless you comment out a large piece of code. Multilinear comments are only used when a long text needs to be commented.

// Good writing
if(condition){
    
    // If the code is executed here, it indicates that all security checks have been passed.
    allowed();
}

// Bad writing
if(condition){
    // If the code is executed here, it indicates that all security checks have been passed.
    allowed();
}

// Bad writing: incorrect indentation
if(condition){
// If the code is executed here, it indicates that all security checks have been passed.
    allowed();
}

// Good writing
var result = something + somethingElse; // SomthingElse should not be null

// Bad Writing: There is no gap between code and comments
var result = something + somethingElse;// SomthingElse should not be null

// Good writing
// if(condition) {
//    doSomething();
//    thenDoSomethingElse();
// }

// Bad writing
// The next piece of code is very difficult, so let me explain it in detail.
// The purpose of this code is to first determine whether Tianjian is true or not.
// Only if it is true will it be executed, provided that it is through
// Calculated by multiple functions throughout the call life cycle
// The whole value can be modified.
if(condition) {
    
    // If the code is executed here, it indicates that all security checks have been passed.
    allowed();
}

2.2 Multi-line Notes

//Legal multi-line comments
 /* My comment*/
/* Another commentary
 This comment contains two lines */
/*
Another note
 This comment also contains two lines
*/

// Higher, clearer. java style annotations
/*
 * Another commentary
 * This comment contains two lines of text
 */

Multi-line annotations always appear before the code segment to be described, and there is no blank line interval between the annotations and the code. Like single-line annotations, there should be a blank line before multi-line annotations, and the indentation level is consistent with the code it describes.

// Good writing
if(condition){
    
    /*
     * If the code snippet is executed here
     * It shows that all security tests have been passed.
     */
    allowed();
}

// Bad Writing: No blank lines before comments
if(condition){
    /*
     * If the code snippet is executed here
     * It shows that all security tests have been passed.
     */
    allowed();
}

// Bad Style: No spaces after asterisks
if(condition){
    /*
     *If the code snippet is executed here
     *It shows that all security tests have been passed.
     */
    allowed();
}

// Bad writing: incorrect indentation
if(condition){

/*
 * If the code snippet is executed here
 * It shows that all security tests have been passed.
 */
    allowed();
}

// Bad Writing: Don't use multi-line comment format at the end of the code
var result = something + somethingElse; /*somethingElse The value should not be null*/

2.3 Use Notes
The general guideline is to add comments when the code is not clear enough and not when the code is clear enough.

2.3.1 Hard to understand code
Difficult code should always be annotated. Depending on the purpose of the code, you can use one-line annotation, multi-line annotation, or mix two annotations. The key is to make it easier for others to read the code. For example, this sample code is extracted from the Y.mix() method in the YUI class library.

// Good writing
if(mode) {

    /*
     * When mode is 2 (prototype-to-prototype, object-to-object), only one recursive execution is performed here.
     * Used to perform prototype-to-prototype merging operations, object-to-object merging operations 
     * It will be suspended and executed at the right time.
     */
    if(mode === 2) {
        Y.mix(receiver.prototype, supplier.prototype, overwrite,
                whitelist, 0, merge);
    }
    
    /*
     * Depending on the specified schema type, we may copy from the meta-object to the prototype.
     * Or copy from the prototype to the recipient
     */
    from = mode === 1 || mode === 3 ? supplier.prototype : supplier;
    to = mode === 1 || mode === 4 ? receiver.prototype : receiver;
    
    /*
     * If the supplier or receiver does not contain prototype attributes,
     * The logic ends and returns undefined if there are prototype properties.
     * Then the logic ends and returns received
     */
    if(!from || !to) {
        return receiver;
    }
}else {
    from = supplier;
    to = receiver;
}

The Y.mix() method uses constants to decide how to deal with it. The mode parameter is one of the constants, but the values alone cannot explain what they represent. The comments here are excellent because they explain the responsible decision logic in time.

2.3.2 Codes that may be mistaken for errors
Another good time to add comments is when the code looks wrong. In team development, there are always good developers who find other people's code errors when editing the code and fix them immediately. Sometimes this code is not the source of the error, so "fixing" this error often creates other errors, so this modification should be traceable. When you write it If the code is likely to be mistakenly tasked by other developers, annotations need to be added.

while(element && (element = element[axis])) {
    if((all || element[]TAG_NAME) &&
            (!fn || fn(elemtnt))) {
        return element;
    }
}

In this example, the developer uses an assignment operator in the while loop control condition. This is not a standard usage and is often considered problematic by the checking tool. If you are not familiar with this code and read it without comment, you may mistake it for a mistake. It is assumed that the author intended to use the comparison operator== rather than the assignment operator= The comments at the end of this line indicate that the author intends to assign rather than compare, so that other developers will not "fix" the code when they read it.

2.3.3 browser feature hack
js programmers often write inefficient, inelegant, thorough dirty code to make low-level browsers work properly. In fact, this situation is a special kind of "code that may be mistaken for error": this kind of code that does not obviously have browser feature Hack may imply some errors. Examples are taken from the Y.DOM.contains() method of the YUI class library.

var ret = false;

if(!needle || !element || !needle[NODE_TYPE] || !element[NODE_TYPE]) {
    ret = false;
}else if(element[CONTAINS]) {
    
    //If needle is not ELEMENT_NODE, there will be errors below ie and safari
    if(Y.UA.opera || needle[NODE_TYPE] === 1) {
        ret = element[CONTAINS](needle);
    }else {
        ret = Y_DOM._bruteContains(element, needle);
    }
}else if(element[COMPARE_DOCUMENT_POSITION]) {
    if(element === needle ||
            !!(element[COMPARE_DOCUMENT_POSITION](needle) & 16)){
        ret = true;
    }
}

return ret;

Line 7 of this code contains an important comment. Although both IE and Safari have built-in methods containing (), this method will fail if needle is not an element. So this method can only be used when the browser is Opera. Needle in other browsers must be an element (nodeType 1). The browser description here also explains why an if is needed. Statement. This comment not only ensures that it will not be mistakenly altered by others in the future, but also makes appropriate adjustments to the compatibility of the new version of IE and Safari when the coder goes back to read his own code.

2.4 Document Annotations
Document annotations are not part of js, but they are widely used. The most popular format is JavaDoc document format: multi-line annotations start with a single slash plus a double asterisk (/**), followed by descriptive information, in which @ symbols are used to represent one or more attributes.

/**
If you need a deep copy, use'clone()'
@method merge
@param {Object} One or more merged objects
@return {Object} A new merged object
**/
Y.merge = function() {
    var args = arguments,
        i = 0,
        len = args.length,
        result = {};
        
    for(; i < len; ++i) {
        Y.mix(result, args[i], true);
    }
    
    return result;
}

All methods

Annotation descriptions should be added to methods, expected parameters, and possible returned values.

All constructors

Annotation descriptions should be added to custom types and expected parameters.

All objects that contain documented methods

If an object contains one or more methods with document annotations, the object should also add document annotations to the document generation tool appropriately.

Posted by kokomo310 on Tue, 08 Jan 2019 09:39:09 -0800