JavaScript Development Specification requirements (canonical code) _ Basics

Source: Internet
Author: User
Tags documentation eval in python
I have in the development work and not according to the norms of the development of colleagues to cooperate with him can not use the "happy" to describe the. Now I write the purpose of this article in addition to share a little experience with you, more is the hope for the future partners can play a certain role in reference. Of course, if I say there are unscientific places also hope that the predecessors of many advice. The following sub-clause lists the various specifications that are proposed for the colleague's coding problem, which may not be mentioned in other specifications agreed by the industry.

1, to ensure that code compression does not make mistakes

For large JavaScript projects, all JavaScript files included in the project are typically compressed at the time the product is released, such as compressing the code with Google Closure Compiler service. The new version of jquery has switched to this tool to compress code, this will generally remove development-written comments, remove all spaces and line-wrapping, and even replace the longer variable names with short and meaningless variable names, in order to speed up the download speed of the file, while also reducing the additional data traffic generated by the Web site access, In addition, the code protection also played a little bit of effect, at least compressed code even if it is not so easy to read. To get the code right through the compression, the general requirements of the sentence to the normal end of the semicolon, curly braces should also be strictly closed, and specifically to see the requirements of compression tools. So if you don't do it at the start, wait for the error and then go back to find the mistake. That's a waste of time.

2, to ensure that the code through the specific IDE's automatic formatting function

Generally more sophisticated development tools (such as Aptana Studio) have code "automatic format" function, this function to help achieve unified line-wrapping, indentation, space and other code choreography, you can set your favorite format standard, such as the opening brace {whether another row. The goal is to make it easier for your development team members to use a copy of your code automatically formatted with the IDE to read in a style he likes or knows. Your co-workers need to read your code, probably because you're writing a generic method, and he uses it in other module development, reading your code to get the most out of the details of method calls and implementations, which is an effect that simple API documents can't achieve.

3, use the standard document annotation

This requirement is the most basic, which is advantageous to see the method at the method call specific parameters of the instructions, you can use the supporting documentation tools to generate HTML or other format development documents for other team members to read, you can try to use Jsdoc-toolkit. If the API you generate automatically comes from an open platform, like the facebook.com application, then your document is for all developers in the world to see. By writing a complete note, it is also easier for team members to read your code, and through your parameter descriptions, team members can easily know how you write the methods involved in implementing the details. Of course, also facilitate the future code maintenance, so even if the big project, after a long time, back to a pity dorado things will not have forgotten their own writing code is how.

4, the use of norms meaningful variable name

Using variable names that are meaningful to the specification can improve the readability of your code, and as a member of a large project developer, the code you write is not just to make it easy for others to read. Development of large projects, in fact, each person to write the amount of code may be relatively large, canonical naming, in the future to see their own code is also clearly understandable, such as the future system upgrades or new features, modify the code to be more relaxed. If the end of the original code to find that they do not understand now, it is really a big joke.

Of course, use a meaningful variable name as much as possible using the standard name, like here: var me = This may not have the var self = This good, because self is the keyword in python, in Python Self is the common language this usage. In the following example, plus S is obviously more scientific than no addition, so you know that the variable name is a plural, possibly an array, etc.:

var li = document.getelementsbytagname (' li ')
var lis = document.getelementsbytagname (' li ')

5. Do not use biased grammar

JavaScript as a dynamic scripting language, flexibility is both advantages and disadvantages, it is well known that different levels of dynamic language developers of the implementation of the same function of the code in the specification or syntax will be a big difference. In any case, the code code less funny, do not complicate simple issues, do not violate the principles of code readability is what we should do.

such as this statement: typeof (b) = = ' String ' && alert (b) should read: if (typeof (b) = = ' string ') alert (b), as in the previous use, using the && Operator Resolution mechanism: If the detection of && before the statement returned false no longer detect the following statements, in the code optimization has also mentioned the most likely to occur first judgment, such as the wording if the conditions are not good, if the conditions are more and long statements, the code is quite poor readability.

Another example: +function (a) {var p = A;} (' a ') should read: (function (a) {var p = A;}) (' a '), in fact, the previous + number in the function is the same as the function-containing () parenthesis, which is a common and easy to understand way to prevent variable contamination, such as the popular JavaScript framework that follows.

Another example of reducing the readability of your code, such as: function Getpostiontxt (type) {return type = = 2? "Wild": (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 unbroken integer starting from 0, then it is simpler to use the array directly, and the result looks much clearer, and you see that multilayer ternary expression nested in front of you is not dizzy.

6, not the statement is not assigned to the place of birth in Chinese

There should be no Chinese in the statement I think the General people know, although this does not affect the operation of the program, but obviously has the back industry standard requirements, of course, we are not in the use of "easy language" to do development. On this issue, I did not want to take it out to say, but I did meet someone to do so, I do not know whether it is because his English is too bad, at least can also use pinyin bar, in addition to seek translation tools to help also a good choice. I give for example below, like the following writing out of the present teaching can also be understood:

this.user[' name '] = ' john ' or this.user. Name = ' John '

7. Define the parameters of a fixed number of functions explicitly

A fixed number of parameters within the function does not use arguments to get parameters, because in this way, the method you define if it contains more than a script, you can not see at a glance what the method accepts parameters and the number of parameters. Like the following:
var $ = function () {return document.getElementById (Arguments[0]);} Should be changed to: var $ = function (elemid) {return document.getElementById (elemid);}

8, do not have to be enthusiastic about dynamic event binding

While knowing that events can be dynamically bound, such as using AddEventListener or the Bind method using jquery, and knowing that dynamic event binding can make XHTML cleaner, I usually recommend writing events directly on the DOM node. I think that makes the code easier to maintain, because by doing so, we can easily see what element binds to the method when we look at the source code, simply saying that it's easier to know what method script a button or link clicks Si cho.

9, reduce the coupling between code and XHTML

Instead of relying too much on some of the DOM's content features to invoke different scripting code, you should define methods for different functions and then call them on the DOM, so that regardless of whether the DOM is a button or a link, the invocation of the method is the same, such as the following implementation is obviously problematic:

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 example above actually handles two things within a function, which should be divided into two functions, like the above, if the link is changed to a button, such as: <input type= "button" onclick= "Mybtnclick (This)" value= "OK "/>, then the Mybtnclick function inside the obj.innerhtml is a problem, because it should be obj.value right now, and if the button name from Chinese to English will also have problems, so this practice problem too much."

10. A function should return a uniform data type

Because Javascrip are weakly typed, some people are more casual about the return type when writing a function, and I think it should go back like a strongly typed language, and look at the following two examples:

function GetUserName (UserID)
{
if (Data[userid])
return Data[userid];
Else
return false;
}

should read:

function GetUserName (UserID)
{
if (Data[userid])
return Data[userid];
Else
Return "";
}

If this method is defined in C #, we know that the data type it is going to return should be a string, so if we don't find the data we should return an empty string instead of returning a Boolean or other inappropriate type. This does not affect the future invocation of the function, because the returned empty string is considered "not" in logical judgment, that is, the same as false, unless we use all equals "= = =" or typeof to judge.

11, the specification defines the JSON object, the complement double quotation mark

It's certainly good to use standards, so why is it that people don't use standards? I think it may be a matter of laziness or habit. I think it makes sense, but not the point, that I might be told that less quotes can reduce the volume of a file. For JSON data returned by the server, use the standard structure to make it easy to view with the Firefox browser's Jsonview plug-in (as in the case of XML tree display), and if you are using jquery for development, the latest version jquery1.4+ has a higher requirement for JSON format , you can check your jquery update documentation for yourself. For example: {name: "Tom"} or {' name ': ' Tom '} should be changed to {"Name": "Tom"}.

12, do not leave the future in the file to determine the code fragment that is no longer used

Once the code has been adjusted or refactored, the code that is no longer in use should be deleted in time, and if the code is considered to have some value, it can be clipped to a temporary file. Stay in the project not only increased the volume of files, this to the other members of the team even their own play a certain interference, afraid of the future to see their own code can not understand what this method is doing, whether there has been used. Of course, you can use the document annotation tag @deprecated to identify this method as not recommended.

13, do not repeat the definition of other team members have implemented methods

For large projects, some development members typically implement common methods, while others familiarize themselves with these common methods and call them directly when they have a call to write their own modules, rather than some developers like to "go it alone" and do not read these common method documents. In their own code to write again, this not only produces superfluous code, of course, it will affect the efficiency of team development, this is not a team spirit of performance, is a repetition of the tragedy of the wheel.

For example, in a generic class file Common.js has a defined function $ (elemid) {return document.getElementById (elemid)} You should not repeat the definition of this function again in mail.js, especially for some complex methods.

14, call the appropriate method

When there are several ways to achieve the same functionality, we still have to choose the most appropriate way to use the scene. Here are two Ajax ways to illustrate the jquery framework. If you determine that the data returned by the server is JSON, you should use $.getjson directly instead of using $.get to get the data and then turn the Eval function into a JSON object. If you do not use $.post because you want to transfer large amounts of data for this request, you should also use the method of specifying the return data type (setting the datatype parameter). If you use $.getjson, we can see at a glance in the code that this request server is returning JSON.

Warm tip: After jQuery1.4, if the server has set the data output ContentType, such as asp.net C # settings Response.ContentType = "Application/json", then $.get will be with $. The use of Getjson is no different.

15, use the appropriate control to store the appropriate data

It has been found that a div was used to save JSON data for future use after the page was downloaded, like this: <div id= "JSON" >{"name": "Tom"}</DIV> Obviously, this div is not used for interface display, and if you have to do this, To achieve the use of HTML files for data caching, at least to use hidden fields to save this data is more reasonable, such as: <input type= "hidden" value= "{" name ":" Tom "}"/>.

In fact, you can also use the Window object to save some data, like the above example, we can directly include such a script block in the AJAX request page: <script>window.userdata = {"Name": "Tom"};</script When the $ ("#MyDiv") is executed in the AJAX request callback function, the variable is immediately available on the window after the HTML (data). If you take the first approach, you will inevitably be eval (document.getElementById ("UserData"). InnerHTML). If you store a large amount of data in a Window object, the data is manually cleaned up in a timely manner, which is not disappearing until the browser is refreshed or restarted, which increases the memory overhead.

16, never ignore code optimization work

Code optimization is the goal that every programmer should strive to achieve, and it should be the eternal pursuit of programmers. Write code, should not rush to realize the function, to think about how to write code, code execution efficiency is better.

For example: Suppose there is a shortcut method for defining getElementById Functoin $ (elemid) {return document.getElementById (elemid)}, then someone might write this code $ ("Mydiv") . Parentnode.removechild ($ ("mydiv")), in fact, performed two times getElementById Dom lookup, if changed to this would be better: var mydiv = $ ("mydiv"); MyDiv.parentNode.removeChild (mydiv). Fortunately getElementById Dom Lookup is relatively fast, if replaced by getElementsByTagName should pay attention to optimization. The jquery development team has also alerted you to this issue.

Of course, code optimization techniques also require personal accumulation. Once a friend told me that he wrote Web site background code has never been considered optimized, because their site is a quad-core Xeon server, I think it is very ridiculous.

17, will analyze the planning document, can use the Object-oriented method for interface definition and code organization

This ability is very important for every programmer, which is an important factor in determining the level of a programmer. Ability to refine and abstract the requirements of different classes, and then methodically write code to make the code structure clear, readable, code easy to maintain, not too procedural and messy, so that is a good programmer.

Author: Webflash
Source: http://webflash.cnblogs.com

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.