JavaScript development specifications reduce code and XHTML Coupling

Source: Internet
Author: User
Tags comment tag

As a developer (WEB Front-end JavaScript development), nonstandard development not only makes code maintenance difficult in the future, but also is not conducive to team cooperation, it usually brings about code security and execution efficiency issues. I have been cooperating with colleagues who do not develop according to standards in my development work, so it cannot be described as "Pleasant" to work with him. Now I am writing this article to share with you a little bit of experience, but more hope to play a certain role for future partners. Of course, if I say something unscientific, I still hope that many predecessors will give me more advice. The following sections list the requirements of various standards. These requirements are raised for the coding problem of colleagues. Other standards agreed by some industries may not be mentioned.

1. Ensure no error after code Compression

For large JavaScript projects, all the JavaScript files contained in the project are compressed during product release. For example, you can use Google Closure Compiler Service to compress the code, the new version of jQuery has used this tool to compress the Code. This usually removes the comments written during development and removes all spaces and line breaks, you can even replace a long variable name with a short and meaningless variable name to speed up file download, at the same time, it also reduces the additional data traffic caused by Website access, and also plays a role in code protection. At least the compressed code is not as easy to understand even if it is restored. To compress the code correctly, it is generally required that the statements should end normally with a semicolon and braces should also be strictly ended. The specific requirements of the compression tool should also be taken into account. Therefore, it would be a waste of time if the compression is not performed according to the standard at the beginning and the error is returned after the compression fails.

2. Ensure that the code can be automatically formatted using the specific IDE

Generally, more sophisticated development tools (such as Aptana Studio) all have the "Automatic formatting" function of code, which helps to implement unified line breaks, indentation, spaces, and other code orchestrations, you can set your favorite format standard, for example, whether the left braces {start with another line. The purpose of achieving this requirement is to help your development team members take a copy of your code and use IDE to automatically format it into a style that they like or are familiar with for reading. Your colleague needs to read your code, probably because you write a general method for it, which should also be used in the development process of other modules, read your code to get the most in-depth understanding of method calls and implementation details, which is not achieved by Simple API documentation.

3. Use standard document annotations

This requirement is the most basic, which helps to see the specific parameter passing prompt of the method in the method call, you can also use the supporting documentation tools to generate development documents in html or other formats for other team members to read. You can try to use jsdoc-toolkit. If the APIS you automatically generate come from an open platform, just like the facebook.com application, your documents are provided to all developers in the world. In addition, you can write complete comments to make it easier for team members to read your code. With your parameter descriptions, team members can easily know how to pass the methods you have written to participate in implementation details. Of course, it is also convenient for code maintenance in the future, so that even if a large project, after a long time, you will not forget the code you wrote when you go back to change something.

4. Use standardized and meaningful variable names

Using standardized and meaningful variable names can improve code readability. As a member of the development of large projects, self-written code should not only be easy for others to understand. For large projects, the amount of code written by each person may be relatively large, with standardized names. In the future, your code can be clearly understood, such as system upgrades or new functions, it is much easier to modify the code. It would be a big joke if I found that I could not understand the code I wrote at the beginning.

Of course, use standard names for meaningful variable names. For example, var me = this may not be as good as var self = this, because self is a keyword in Python, in Python, self is the common language of this. Let's look at the following example. The addition of s is obviously more scientific than the absence of addition, so that we can know that the variable name is stored in the plural, maybe an array, and so on:

Var li = document. getElementsByTagName ('lil ')

Var lis = document. getElementsByTagName ('lil ')

5. Do not use biased syntax

As a dynamic scripting language, JavaScript has both advantages and disadvantages. As we all know, developers at different levels of dynamic languages may significantly differ in the specification or syntax of code written to implement the same function. In any case, the standard encoding is less funny, and the simple problem is not complicated, and the principle of easy coding is not violated.

For example, the statement typeof (B) = 'string' & alert (B) should be changed to: if (typeof (B) = 'string') alert (B ), in the previous usage, the & operator parsing mechanism is used: If the & Pre-statement returns false, the following sentence will not be detected, in terms of code optimization, It is also mentioned that the most likely case should be judged first. For example, if there are few good conditions for writing, if there are many conditions and long statements, the code is quite readable.

Another example: + function (a) {var p = a;} ('A') should be changed to: (function (a) {var p = ;}) ('A'). In fact, the plus sign in front of the function has the same effect as the () bracket containing the function, and is used for computing priority, the latter is a common and easy-to-understand approach to prevent variable pollution. For example, some popular JavaScript frameworks adopt the following method.

Another example of reducing code readability is: function getPostionTxt (type) {return type = 2? "Field": (type = 3? "Mall": (type = 4? "Copy": null);} should be changed to: function getPostionTxt (type) {var typeData = {"2": "wild", "3": "mall ", "4": "copy"}; if (typeData [type]) return typeData [type]; else return null ;}. If type is an uninterrupted integer starting from 0, it is easier to directly use the array. This result looks much clearer. Do you see the nested headers of the preceding multi-layer ternary expressions not dizzy.

6. A Chinese character is not born in a place where the statement is not assigned a value.

The statement should not contain Chinese characters. I think most people know that although this does not affect the program running, it is clear that there are industry-standard requirements. Of course, we are not using "easy language" for development. I didn't want to give it out, but I did not know whether it was because his English was really bad, at least pinyin can be used. In addition, it is a good choice to seek help from translation tools. I will give an example as follows, which can be understood as follows:

This. user ['name'] = 'zhang san' or this. user. Name = 'zhang san'

7. Define a fixed number of parameters for a function

A function with a fixed number of parameters does not use arguments to obtain parameters, because in this way, if the method you define contains more scripts, you cannot see at a glance what parameters and the number of parameters are accepted by this method. For example:

Var $ = function () {return document. getElementById (arguments [0]);} should be changed to: var $ = function (elemID) {return document. getElementById (elemID );}

8. Do not be keen on dynamic event binding

Although we know that events can be dynamically bound, such as using addEventListener or using jQuery's bind method, we also know that dynamic event binding can make XHTML clean, however, in general, it is recommended that you write the event on the DOM node directly. In my opinion, this can make the code easier to maintain, when viewing the source code, we can easily know what Element is bound to and what method script is called when a button or link is clicked.

9. Reduced code and XHTML Coupling

Instead of relying too much on some content features of the DOM to call different script codes, you should define methods for different functions and then call them on the DOM, regardless of whether the DOM is a button or a link, methods are called in the same way. For example, the following implementation may obviously have problems:

Function myBtnClick (obj)

{

If (/OK/. test (obj. innerHTML ))

Alert ('OK ');

Else if (/cancel/. test (obj. innerHTML ))

Alert ('cancel ');

Else

Alert ('other ');

}

<A herf = "javascript:;" onclick = "myBtnClick (this)"> OK </a> <a herf = "javascript:;" onclick = "myBtnClick (this) "> cancel </a>

The above example actually processes two things in a function and should be divided into two functions, such as the above statement. If you change the link to a button, for example, change it to the following: <input type = "button" onclick = "myBtnClick (this)" value = "OK"/>, the obj IN THE myBtnClick function. innerHTML has a problem because obj. value is correct. If you change the button name from Chinese to English, there will be too many problems.

10. A function should return a unified data type.

Because JavaScrip is of a weak type, some users may be casual in processing the returned type when writing functions. I think it should be returned like a strong type language. Let's look at the two examples below:

Function getUserName (userID)

{

If (data [userID])

Return data [userID];

Else

Return false;

}

It should be changed:

Function getUserName (userID)

{

If (data [userID])

Return data [userID];

Else

Return "";

}

If this method is defined in C #, we know that the data type to be returned should be a string, so if this data is not found, we should return an empty string, instead of returning a Boolean value or its unsuitable type. This does not affect future function calls, because the returned null string can be regarded as "non" in logic judgment, that is, it is the same as false, unless we use "=" or "typeof.

11. Define JSON objects with double quotation marks

It is certainly advantageous to use standards. Why do we still choose not to use standards? I think this may be a problem of laziness or habit. Someone may tell me that writing less quotation marks can reduce the file size. I think this is reasonable but not important. For JSON data returned by the server, you can use the JSONView plug-in of the Firefox browser to conveniently view the JSON data (as shown in the XML tree). In addition, if you use jQuery for development, the latest version of jQuery1.4 + has higher requirements on the JSON format. For details, refer to the jQuery update document. For example, {name: "Tom"} or {'name': 'Tom '} should be changed to {"name": "Tom "}.

12. Do not leave a code snippet in the file that will not be used in the future

After the code is adjusted or restructured, the previously written code that is no longer used should be deleted in a timely manner. If you think the Code has some useful value, you can cut it into a temporary file. Staying in the project not only increases the file size, but also interferes with other members of the team and even themselves. I am afraid that I will not understand what this method will do if I look back at the code in the future, used. Of course, you can use the document comment tag @ deprecated to mark this method as not recommended.

13. Do not repeatedly define methods already implemented by other team members

For large projects, some developers usually implement some general methods, while others should be familiar with these general methods, then, you can directly call the module when you need to call it. Instead of reading these general method documents, some developers prefer "Single-stick, I wrote the implementation again in my own code, which not only produces redundant code, but also affects the development efficiency of the team. This is a result of no team spirit, it is the tragedy of repeating the wheel.

For example, in the Common class file Common. js has a defined function $ (elemID) {return document. getElementById (elemID)} Should Not Be in Mail. the repeated definition of this function is repeated in js, which should be more appropriate for some complicated methods.

14. Call appropriate methods

When several methods can implement similar functions, we should choose the most appropriate method based on the scenario. The following describes two AJAX methods of the jQuery framework. If you confirm that the data returned by the server is JSON, you should directly use $. getJSON instead of using $. get to get the data and convert it to a JSON object using the eval function. If $. post cannot be used because this request needs to transmit a large amount of data, you should also specify the data type returned (set the ype parameter. If $. getJSON is used, we can see at a glance in the code that the request server returns JSON.

Tip: After jQuery1.4, if the server has a ContentType set for data output, such as ASP. net c # Set Response. contentType = "application/json", then $. get will match $. there is no difference in the use of getJSON.

15. Use appropriate controls to store suitable data

It was found that someone used DIV to save JSON data for future use after the page is downloaded, like this: <div id = "json"> {"name ": "Tom"} </div>, it is clear that this DIV is not used for interface display. If you have to do so, it can cache data using HTML files, it is more reasonable to use hidden fields to store this data, for example, <input type = "hidden" value = "{" name ":" Tom "}"/>.

In fact, you can also use the window object to save some data. In the example above, we can directly include such a script block on the AJAX request page: <script> window. userData = {"name": "Tom" };</script>. After $ ("# MyDiv" ).html (data) is executed in the AJAX request callback function, this variable is available immediately on the window. If the first method is used, eval (document. getElementById ("UserData"). innerHTML) is inevitable ). If the window object stores a large amount of data, you need to manually clean the data in time when it is not used. They will disappear after the browser refreshes or restarts, which will increase the memory overhead.

16. Never ignore code optimization

Code optimization is the goal that every programmer should strive to achieve. It should also become the permanent pursuit of programmers. When writing code, you should not rush to implement the function. If you want to write code, the code execution efficiency is better.

For example, suppose there is a shortcut for defining getElementById functoin $ (elemID) {return document. getElementById (elemID)}, someone may write this code $ ("MyDiv "). parentNode. removeChild ($ ("MyDiv"), in fact, the getElementById DOM query is executed twice here. It will be better if it is changed to this: var myDiv = $ ("MyDiv"); myDiv. parentNode. removeChild (myDiv ). Fortunately, the DOM search for getElementById is relatively fast. If you replace it with getElementsByTagName, you should pay more attention to optimization. The jQuery development team also reminded everyone to pay attention to this issue.

Of course, code optimization skills also need to be accumulated by individuals. A friend once told me that he never thought about optimization when writing website back-end code, because their website uses Xeon quad-core servers, which I think is ridiculous.

17. Analysis of planning documents, interface definition and code organization using object-oriented methods

This capability is very important for every programmer. It is also an important factor that determines the level of a programmer. The ability to refine requirements and abstract different classes, and then write code in a systematic manner, so that the code structure is clear and readable, and the code is easy to maintain. It is not too procedural and messy, this is a good programmer.

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.