1 features of the maintainability code
- Understandable: Other people can take over the code and understand its intentions without the original developer spending too much time explaining it!
- Intuition: Things in the code can be understood at a glance, although the process is complex.
- Adaptability: Code with a change in data does not require a full override method.
- Extensibility: The ability to extend the core functionality on the code architecture.
- Tunable: When an error occurs, the code can give you enough information to directly determine where the problem is.
2 Code Conventions
Because of the JavaScript language, we can write code in a variety of programming styles, from the traditional object-oriented to declarative-to-functional. The formation of a good set of JavaScript code writing conventions can greatly improve maintainability, which is absolutely no place for beginners to pay attention to.
2.1 Readability
- Indentation: Uniform code indentation in the project, easier to read, a nice and common indentation size of four spaces, of course, can be other quantities.
- Note: In fact, we are writing some background code that will often comment on a function, a business logic, a function code, but we are writing JavaScript but often ignore these habits. In general, in JS there are the following places to note:
- Functions and methods: Describes their purpose and parameter representations, return values, and so on.
- Large segment of code: a large segment of code is usually a task code, which should be commented to describe the task.
- Complex algorithm: Not everyone will be your algorithm, you need to put your algorithm ideas briefly described below.
- Hack: Because of browser differences, JavaScript's Hack is used to address what issues should be described clearly.
2.2 Naming of variables and functions
- Variable names should be nouns: such as Car,person
- The function name should start with a verb: such as getname (), a function that returns a Boolean type value is usually preceded by the IS, such as: isenable ();
- As long as it is logical to not worry about the length of the variable or function name, the length problem can be resolved by the time you release the code to compress it.
2.3 Variable Type Transparency
var //Declaration of two variables
As in the code, because the variables in JavaScript are loosely typed, we don't know what type of data the car and person are, and we can mitigate the problem in two ways:
-
Initializes the variable: The specified variable type is initialized, but an object named in this way cannot be used for a parameter in a function declaration.
var car = null ; Span style= "color: #93A1A1;" >//car is the object var person = "; //person is a string var count =-1 ; //count is an integer var found = false ; //found is a Boolean
-
Hungarian notation: Precede the variable name with one or more characters to represent the data type. O-Object, S-string, I-integer, F-floating-point, B-Boolean
var //car is an object var //person is a string var //count is an integer var //found is a Boolean type
3 Loose coupling
Remember when I first started C #, my brother often told me, ' high cohesion low coupling ' the word, I also vague nodded, many people may also like me before, this word familiar, but not really practice.
As long as one part of the application relies too much on another, the code is too tightly coupled and difficult to maintain! Typical problem: The object applies another object directly, and modifies one of the other. In our web application, we can decouple our code in a way:
3.1 Decoupling Html/javascript
In web apps, we want HTML to focus on presenting data, CSS focusing on styling, and JavaScript focusing on behavioral interactions. But there is some code that is too tightly coupled with HTML and JavaScript.
-
Write directly to JavaScript in HTML, use the <script> element with inline code, or use HTML attributes to assign an event handler.
<!--tightly coupled--> using <script> tags; <script type = "Text/javascript" document . Write ( "Hello, JavaScript ' ); </script ; <!-- Tightly coupled--> using time-handler property values; <input Type = value = "click me" onclick = "dosomething ()" />
Although this is completely true, the JavaScript error is that we need to determine whether the error occurred in HTML or JavaScript, and there is a time difference, when I press the button on the above code, if the JavaScript code is not loaded, The change back now throws an error. In practice, the ideal situation should be that HTML and JavaScript should be completely detached, using the introduction of external files to load JavaScript.
-
Conversely, you can't include too much HTML in JavaScript
function insertmsg (msg) var document. getElementById (' container '); ' <div lcass=\ ' msg\ ' ><p class=\ ' post\ ' > ' ' </p></div> '
When you are writing this code, I think you should find a JS template engine.
Dynamically generated HTML, to write CSS layout, positioning errors are more difficult to control.
3.2 Decoupling Css/javascript
Above said, CSS and JS should do their own duties, not too much intimate action, Su-eun love, die quickly embarrassing ~ ~ ~.
This problem does not say completely decoupling CSS and JS, because JavaScript is often needed in modern web applications to change styles, but we try to keep them separate.
//CSS tight coupling to JS ' Red ' ' Blue ';
Such code in the future to modify the style when the CSS and JS need to be modified, can be troublesome.
//This will be OK. ' Color ' //color is a style class
Another thing is that you can't write CSS expressions in CSS, which should all be known.
3.3 Decoupling application logic and event handlers
Each Web application has a considerable number of event handlers listening to a large number of different events, however, it is seldom possible to carefully detach the application logic from the event handlers as follows:
function CheckValue (e) { windowvarif5//Omit a heap of logical processing code ...}}
Rewrite the above code to:
function CheckValue (value) if 5 //Omit a heap of logical processing code ... } functionhandleblur(e){ windowvar target = E.target | | e.srcelement; //Invoke application logic handler }
What good is this writing?
- When there are different ways to trigger the same process event, just invoke the application logic handler.
- Application logic handlers can be tested individually without adding to the event.
4 Programming practices
Web applications created in an enterprise environment are often authored together by a large number of people. The goal in this case is to ensure that the browser environment used by everyone has consistent and unchanging rules, so we need to stick to some programming practices:
4.1 Avoiding global variables
In a JS file, a maximum of one global variable is allowed, so that other objects and functions are included, because too many global variables consume a lot of memory.
//Two global variables var ' Jozo ' functionsayname() { alert (' Jozo ');}
The above code has two global variables, the variable name and the function sayname (), you can actually create a variable containing them:
//A global variable--recommended var person = { name:' Jozo ', function(){ alert (this . name);} }
Such a global variable extends to ' the concept of space ' and does not conflict with other features, helping to eliminate confusion between functional scopes.
4.2 Avoiding comparisons with null
function Sortarray (values) if null) { Values.sort (comparison function);} }
The IF statement in the above code should detect if values are arrays, but if compared to null, strings, numbers, and so on will pass, causing the function to throw an error. Here is the array, then we should check if it is an arrays:
function Sortarray (values) if instanceof Array) { Values.sort (comparison function);} }
When we encounter code that compares to NULL, we should replace it with the following technique:
- If the value is a reference type, the constructor is checked with the instanceof operator.
- If the value is a base type, the TypeOf operator is used to check its type.
4.3 Using constants
Validate (value) if (! value) { alert (' does not exist '); '/errors/invalid.php '; }}
Now, I want to change the ' not present ' to ' the data does not exist! ' ', change the jump path, I have to go back to the function to find the corresponding code to modify, and each time the logic code changes, it is possible to introduce the risk of errors. So we can define the data separately as constants, separated from the application logic:
var Constans = { ' does not exist ', errorpage:'/errors/invalid.php 'validate(value )if(! Value) { alert (constans.errormsg); Location.href = Constans.errorpage; }}
This allows us to modify the static text content without having to move the logic function, or even constans a single file. So what kind of data needs to be extracted to make constants?
- Duplicate value: Any value that is used in multiple places.
- User interface string: Any string that is used to display user prompt information.
- URLs: In a Web project, the resource path may change frequently. Save it in a public place and make it easier to change it!
- Any value that might change in the future.
5 Summary
All programming languages require well-maintainable code, which is important because most developers spend a lot of time maintaining code for others. In order to alleviate the burden of each other, from today I will be a good person, write good code! O (╯-╰) o
[JS advanced] Write maintainability code