What is maintainable code?Maintainable code needs to follow the following characteristics. 1. Understandability - Others can take the code and understand its intent and general path. Code ConventionsAn easy way to make your code maintainable is to develop a set of writing conventions for JavaScript code. Because of the adaptability of JavaScript, coding conventions are important to it. The following subsections discuss an overview of coding conventions. 1. ReadabilityFor code to be maintainable, it must first be readable. Most of the readability is related to code indentation. Neatly indented code can tell at a glance which function the code block belongs to. A very common indentation size is 4 spaces. Now most editors also support one-line formatting of code. Another aspect of readability is comments. Generally speaking, there are some places that need comments.
2. Naming variables and functionsThe most troublesome thing in daily development is naming, whether it is the naming of classes or the naming of some variables and methods, so sometimes we have to rely on some translation software to help with naming. Properly naming variables and functions is very important to increase the understandability and maintainability of your code. The naming rules are generally as follows:
3. Transparent variable typesSince variables in JavaScript are loosely typed, it is easy to forget what type of data a variable contains. Appropriate naming can alleviate this problem to a certain extent, but it is not enough in all cases. There are three other ways to use variable data to represent data types. 3.3.1 Initialization When a variable is defined, it should be initialized with a value that indicates how it should be used in the future. //Specify variable type by initialization var found=false; //Boolean type var count=-1; //Number type var name=""; //String var person=null; //Object 3.3.2. Specifying variable types using Hungarian notation Hungarian notation precedes the variable name with one or more characters that indicate the data type. The most traditional Hungarian notation in JS uses a single character to represent basic types: 0-object, s-string, i-integer, f-floating point number, b-Boolean type. // Hungarian notation for specifying data types var bFound // Boolean var iCount; // Number var sName; // String var oPerson; // Object The advantage of Hungarian notation is that function parameters can also be used, but its disadvantage is that it makes the code somewhat difficult to read. 3.3.3. Using type annotations The final way to specify the type of a variable is to use a type annotation. Type annotations are placed to the right of the variable name, but before the initialization. // Type annotation for specifying types var found /*Boolean*/ = false; var count /*int*/ = 10; var name /*String*/ = "Tom"; var person /*Object*/ = null; Disadvantage: Multi-line comments will conflict with code blocks These three common methods of specifying variable data types each have their own advantages and disadvantages. You can evaluate them based on your own project and then use them. You can also learn to use TypeScript. Loose couplingWhenever one part of an application is overly dependent on another part, the code is occasionally too tight and difficult to maintain. Because of web application technology, there are many situations that can make it too tightly coupled, so you should avoid these situations and maintain loosely coupled code as much as possible. 1. Decouple HTML/JavaScriptJavaScript directly in HTML, using the <script> element with inline code, or using HTML attributes to assign event handling order are all too tightly coupled. Take a look at the following code <button onclick="doSomeThing()">Click Me</button> In this example, the button may be pressed before the doSomeThing() function is available, causing JS errors, because any changes to the button behavior will affect both HTML and JS, affecting maintainability. Similarly, js contains a lot of HTML // Tightly couple HTML to JS function insertMessage(){ document.getElementById('container').innerHTML='<div>Hello World</div>' } This code method will dynamically generate a code block and insert it into the page. It is often difficult to locate errors in the code. Decoupling HTML and JavaScript saves time during debugging, makes it easier to identify the source of errors, and reduces maintenance effort: changing behavior only requires changing in the JavaScript file, and changing markup only requires changing in the rendered file. 2. Decouple CSS/JavaScriptAnother web layer is css, which is mainly responsible for the display of the page. JavaScript and CSS are also very closely related: they are both layered on top of HTML, and therefore often used together. However, as with HTML and JavaScript, CSS and JavaScript can become too tightly coupled. The most common example of tight coupling is using JavaScript to change some styles, like this: // Tight coupling of CSS to JavaScript element.style.color = "red"; element.style.backgroundColor = "blue"; When encountering this kind of direct modification of CSS style, we can control the style more conveniently by directly modifying the element tag class name. 3. Decouple application logic/event handlersEach web application typically has quite a few event handlers, listening for numerous different events. However, few are careful enough to separate application logic from event handlers. 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"; } } } This event handler contains not only application logic, but also handles events. The problem with this approach is twofold. First, there is no way to execute application logic except through events, which makes debugging difficult. What if the expected results do not occur? Does it mean that the event handler was not called or does it mean that the application logic failed? Second, if a subsequent event triggers the same application logic, the functional code must be duplicated or extracted into a separate function. Either way, you'll be making more changes than are actually necessary. A better approach is to separate the application logic and the event handler so that each handles its own thing. An event handler should extract relevant information from the event object and pass that information to a method that handles the application logic. For example, the previous code could 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); } } Several principles for loose coupling between application and business logic:
Keeping these few things in mind can greatly improve the maintainability of any code, and opens up many possibilities for further testing and development. Programming PracticeWriting maintainable JavaScript is not just about how you format your code; it's also about what your code does. Web applications created in an enterprise environment are often authored by a large number of people working simultaneously. The goal in this case is to ensure that everyone has consistent and unchanging rules for their browser environment. Therefore, it is better to stick to some of the following programming practices. 1. Respect object ownershipThe dynamic nature of JavaScript allows almost anything to be modified at any time. Perhaps the most important programming practice in an enterprise environment is to respect object ownership, which means you cannot modify objects that you do not own. Simply put, if you are not responsible for creating or maintaining an object, its objects, or its methods, then you cannot modify them. More specifically:
2. Avoid global variablesClosely related to respecting object ownership is avoiding global variables and functions whenever possible. It's also about creating a consistent and maintainable environment for script execution. At most, create a global variable for other objects and functions to exist in. Consider the following example: // Two globals - avoid! ! var name = "Nicholas"; function sayName(){ alert(name); } This code contains two global variables: the variable name and the function sayName(). In fact, you can create an object that contains both, as shown in the following example: // A global variable - recommended var MyApplication = { name: "Nicholas", sayName: function(){ alert(this.name); } }; This rewritten code introduces a single global object, MyApplication, to which both name and sayName() are attached. This eliminates some of the problems that existed in the previous code. First, the variable name overrides the window.name property, which may conflict with other functions; second, it helps eliminate confusion between function scopes. Calling MyApplication.sayName() logically implies that any problems with the code can be identified by examining the code that defines MyApplication. 3. Use constantsThe following types of values are suitable for defining using constants:
The above is the detailed content of teaching you how to write maintainable JS code. For more information about writing maintainable JS code, please pay attention to other related articles on 123WORDPRESS.COM! You may also be interested in:
|
<<: Analysis of MySQL lock mechanism and usage
>>: A solution to the abnormal exit of Tomcat caused by semaphore
Table of contents 1. Knowledge description of the...
This old question has troubled countless front-end...
Table of contents summary Environment and tool pr...
This article uses examples to illustrate the comm...
<br />Previous article: Web Design Tutorial ...
Sometimes you need to access some static resource...
Preface Some people have asked me some MySQL note...
<p><b>This is bold font</b></...
question: When developing the Alice management sy...
This article mainly introduces an example of how ...
Install Required Files Yum install openssl-* -y C...
lsof (list open files) is a tool to view files op...
Table of contents 1 Version and planning 1.1 Vers...
Robots.txt is a plain text file in which website ...