"JS elevation" - the code to teach you how to write maintainable

1 Introduction

  In the usual development work, most developers spend a lot of time in the maintenance of the code of other personnel. It is difficult to develop a new code from scratch, many cases are based on the results of others based on, modify or add requirements to write their own code that will be called by other developers, so to write a high-quality, maintainable code It is very important.

2, What is the code maintainable

Maintainable code needs to follow the following characteristics.

1. intelligibility - others can take over the code and understand its intent and general way.
2. Intuitive - something the code one can understand, no matter how complicated its operation.
3. Adaptability - the code does not require a change in a data writing method of a complete rewrite.
4. Scalability - have been taken into account in future be extended to allow for core functionality on the code architecture.
5. debuggability - When there goes wrong, the code can give you enough information quickly and directly to find out where the problem lies.

3, coding conventions

  Simply become a way to make the code maintainable is to form a set of JavaScript code writing conventions. Due to the adaptability JavaScript code agreed it is very important. The following sections discuss the introduction of code conventions.

1. readability

  Code may make maintenance, it must first read. Most of the content and readability of code indentation related code can see at a glance neatly indented code block is part of the function, it is common indentation size of 4 spaces, and now most editors also support a member formatting code. Readability is a comment on the other hand, in general, we have the following comments to local needs.

  • Functions and methods - each method should include a comment or annotation, for purposes of description of the algorithm which is used to complete the task, and may be used.
  • A large segment of code - multiple lines of code for accomplishing a single task to be discharged annotation task described in the foregoing.
  • Complex algorithm - to solve a problem using a unique way to be annotated to explain how to do.
  • Hack - browser compatibility process.

Naming variables and functions

  In the words of the normal development of the most irritating thing in the name, or whether it is class named variables and methods of naming, so sometimes had to rely on some of the translation software to help name. Appropriate to name the variables and functions to increase the understandability and maintainability of the code is very important. Naming rules are generally as follows:

  • Variable names should be nouns, such as car or person.
  • Function name should begin with a verb, such as getName ().
  • Function returns a Boolean type is generally used at the beginning, such as isEnable ().
  • Constants should be expressed in all caps, as MAX_LENGTH.

3. Variable type transparent

  Since in JavaScript variables are loose type, it is easy to forget the type of data contained in a variable. Suitable naming a certain extent, can alleviate this problem, but put all the situation is not enough, there are three variables to represent data in data types.

3.3.1 initialization

  When defining a variable later, it should be initialized to a value, to suggest how it should be applied in the future.

// 通过初始化指定变量类型
var found=false; //布尔型
var count=-1; //数字型
var name=""; //字符串
var person=null; //对象

3.3.2, using the specified variable type Hungarian notation

  Hungarian notation before the variable name with the one or more characters to represent the data type. JS most traditional Hungarian notation is used to represent a single character basic types: 0- objects, s- string, i- integer, f- float, b- Boolean type.

// 用于指定数据类型的匈牙利命名法
var bFound //布尔型
var iCount; //数字型
var sName; //字符串
var oPerson; //对象

Hungarian notation benefit is a function of the same parameters can be used, but the drawback is that it allows the code to read that to some extent.

3.3.3, using the type annotations

  The last specifies the variable type is to use type annotations. Notes on the right types of variable names, but in front of the initialization.

// 用于指定类型的类型注释
var found /*Boolean*/ = false;
var count /*int*/ = 10;
var name /*String*/ = "Tom";
var person /*Object*/ = null;

Cons: multiline comment will conflict with the code block

The three common types of data specified variable methods have their own advantages and disadvantages, and then be evaluated for use, you can also learn to use under TypeScript according to their own projects.

4, loose coupling

  As long as a part of the application of excessive reliance on another part of the code it is occasionally too tight, difficult to maintain. Because Web application technology, there are many cases back to make it too tight coupling, and therefore should avoid these situations, and maintain weak coupling of code as possible.

1. decoupled HTML / JavaScript

  JavaScript directly in HTML, containing inline code <script>elements or HTML attributes assigned event processing procedure, are too tightly coupled.
Consider the following code

<button onclick="doSomeThing()">Click Me</button>

  In this example, may doSomeThing () before the function is available, the button has been pressed, resulting in js error, because any changes to the button behavior to be simultaneously touching HTML and js, affect maintainability.

Similarly js contains a large number of HTML

// 将HTML紧密耦合到js中
function insertMessage(){
  document.getElementById('container').innerHTML='<div>Hello World</div>'
}

A method of dynamically generated code block of code inserted into the page, when the code error is often difficult to locate.

HTML and JavaScript decoupling can save time during commissioning, easier to determine the source of the error, but also reduce the difficulty of maintenance: the need to change behavior only in the JavaScript file, and then change the mark as long as the rendered file

2. Decoupling CSS / JavaScript

  Another Web layer is CSS, which is mainly responsible for the page display. JavaScript and CSS is also very closely related: they are above the level of HTML, so often used together. However, the case of HTML and JavaScript and like, CSS and JavaScript may be too tightly coupled. The most common example is tightly coupled to change some style to use JavaScript, as follows:

//CSS 对 JavaScript 的紧密耦合
element.style.color = "red"; 
element.style.backgroundColor = "blue";

In such directly modify the css styles, we can directly be controlled more easily by modifying the style element tag class class name.

3. decouple application logic / event handlers

  Each Web application generally have a considerable number of event handlers, monitor numerous different events. However, few could have carefully separates application logic from the event handler. Consider the following example:

function handleKeyPress(event) {
        event = EventUtil.getEvent(event);
        if (event.keyCode == 13) {
            var target = EventUtil.getTarget(event);
            var value = 5 * parseInt(target.value);
            if (value > 10) {
                document.getElementById("error-msg").style.display = "block";
            }
        }
    }

  In addition to this event handler contains the application logic, also had to handle the event. The problem with this approach has its dual nature. First, in addition to the event will have no method by executing application logic, which makes debugging difficult. If the expected results did not happen how to do? Does it mean that the event handler is not called or refer to the application logic fail? Secondly, if a subsequent event triggered same application logic, you must copy the code or the function code drawn into a separate function. Either way, it must make more changes than necessary.

  A better approach is the application logic and event handlers phase separation, respectively, so that both processes a respective things. An event handler should extract the relevant information from the event object, and transmits the information to a method for processing application logic. For example, the previous code can be rewritten as:

 function validateValue(value) {
        value = 5 * parseInt(value);
        if (value > 10) {
            document.getElementById("error-msg").style.display = "block";
        }
    }

    function handleKeyPress(event) {
        event = EventUtil.getEvent(event);
        if (event.keyCode == 13) {
            var target = EventUtil.getTarget(event);
            validateValue(target.value);
        }
    }

Application and business logic loose coupling between several principles:

  • Do the event object to the other methods; transmit only desired data from the event object;
  • Anything that should be carried out without performing any event handler in the application-level action;
  • Any event handlers should handle the event, then transferred to the processing application logic.

Keep in mind that a few may have gained greatly improved maintainability in any code, and created a lot of possibility for further testing and development.

5, programming practice

  Writing maintainable JavaScript is not just about how to format the code; it also relates to the question of what the code does. Web applications created in the enterprise environment often simultaneously with the creation of large numbers of people. Target in this case is to ensure that the rules of each person using the browser environment have a consistent and unchanging. So, best to stick to some of the following programming practices.

1. Respect object ownership

  The dynamic nature of JavaScript makes almost anything can be modified at any time. Perhaps the most important in a corporate environment programming practice is to respect the ownership of the object, which means that you can not modify the objects do not belong to you. Simply put, if you are not responsible for creating or maintaining an object, its object or its methods, then you can not modify them. more specifically:

  • Do not add an instance or prototype property;
  • Do not add an instance or prototype method;
  • Existing methods do not redefined.

2. Avoid Global Variables

  Closely related to the respect of the ownership of the object as much as possible to avoid global variables and functions. This is also related to the creation and maintenance of a consistent environment for script execution. Create up to a global variable, so that other objects and functions which exist. Consider the following example:

// 两个全局量——避免!!
var name = "Nicholas"; 
function sayName(){ 
 alert(name); 
} 

This code includes two global amount: variable name and function sayName (). In fact, both may create an object comprising, in the following example:

// 一个全局量——推荐
var MyApplication = { 
 name: "Nicholas", 
 sayName: function(){ 
 alert(this.name); 
 } 
}; 

  This rewriting of code introduced into a single global object MyApplication, name and sayName () are attached thereto. Doing so eliminates some problems exist in the previous paragraph code. First, the variable name covering window.name property, may conflict with other functions; secondly, it will help eliminate confusion between the functional scope. Call MyApplication.sayName () logically implies that any problem code can be determined by examining the definition of MyApplication code.

3. Use Constants

Some values ​​for the following types of constants used to define:

  • Repeat value - any value in many uses should be extracted as a constant. This limits the error when a value is changed while the other has not changed when the cause of. It also contains a CSS class name.
  • String user interface - any character string for display to the user, it should be extracted to facilitate international.
  • URLs - In Web applications, resource location is easy to change, it is recommended to use a common place to store all of the URL.
  • Any value may be changed - every time you use literal values, you have to ask yourself is this value in the future will not change. If the answer is "yes", then this value should be extracted as a constant.

These are read "JS elevation" some notes, but also to reflect on their own existence in the usual project development issues. It seems to improve some basic coding tips, write maintainable code is still very necessary.


Reference:
"Advanced JavaScript Tutorial"

Guess you like

Origin www.cnblogs.com/peerless1029/p/11846404.html