Teach you how to write maintainable JS code

Teach you how to write maintainable JS code

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.
2. Intuitiveness - The code should be understandable at a glance, no matter how complex the operation is.
3. Adaptability - Code is written in such a way that changes in data do not require a complete rewrite.
4. Scalability - The code architecture has been designed to allow for future expansion of core functionality.
5. Debuggability - When something goes wrong, the code gives you enough information to quickly and directly find the problem.

Code Conventions

An 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. Readability

For 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.

  • Functions and Methods - Each method or function should contain a comment describing its purpose and the algorithm it may use to accomplish the task.
  • Large blocks of code - multiple lines of code that accomplish a single task should be preceded by a comment describing the task.
  • Complex algorithms - use unique ways to solve a problem and are annotated to explain how they do it.
  • Hack-browser compatibility processing.

2. Naming variables and functions

The 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:

  • Variable names should be nouns such as car or person.
  • Function names should start with a verb, such as getName().
  • Functions that return Boolean types usually start with is, such as isEnable().
  • Constants should be written in all uppercase letters, such as MAX_LENGTH.

3. Transparent variable types

Since 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 coupling

Whenever 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/JavaScript

JavaScript 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/JavaScript

Another 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 handlers

Each 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:

  • Do not pass the event object to other methods; only pass the required data from the event object;
  • Any action that can be performed at the application level should be possible without executing any event handlers;
  • Any event handler should process the event and then hand off processing to the application 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 Practice

Writing 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 ownership

The 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:

  • Don't add properties to instances or prototypes;
  • Do not add methods to instances or prototypes;
  • Do not redefine existing methods.

2. Avoid global variables

Closely 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 constants

The following types of values ​​are suitable for defining using constants:

  • Repeating values ​​- Any value used in more than one place should be extracted into a constant. This limits the chances of errors that can occur when one value changes and the other does not. This also includes CSS class names.
  • User interface strings - Any strings that are displayed to the user should be extracted to facilitate internationalization.
  • URLs - In web applications, resource locations can change easily, so it is recommended to have a common place to store all URLs.
  • Any value that might change - Whenever you use a literal value, you should ask yourself if the value might change in the future. If the answer is "yes", then the value should be extracted as a constant.

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:
  • Writing Maintainable Object-Oriented JavaScript Code
  • Using JavaScript to create maintainable slideshow code
  • Let's talk about what JavaScript's URL object is
  • Detailed explanation of the practical application of regular expressions in JavaScript
  • How to implement an array lazy evaluation library in JavaScript
  • Detailed explanation of the command mode in Javascript practice
  • How to make your own native JavaScript router
  • How to Learn Algorithmic Complexity with JavaScript
  • Use a few interview questions to look at the JavaScript execution mechanism

<<:  Analysis of MySQL lock mechanism and usage

>>:  A solution to the abnormal exit of Tomcat caused by semaphore

Recommend

MySQL Series Database Design Three Paradigm Tutorial Examples

Table of contents 1. Knowledge description of the...

How to make a div height adaptive to the browser height

This old question has troubled countless front-end...

VMware ESXI server virtualization cluster

Table of contents summary Environment and tool pr...

Detailed explanation of common usage of MySQL query conditions

This article uses examples to illustrate the comm...

...

Web Design Tutorial (6): Keep your passion for design

<br />Previous article: Web Design Tutorial ...

Nginx local directory mapping implementation code example

Sometimes you need to access some static resource...

Implementation of adding remark information to mysql

Preface Some people have asked me some MySQL note...

Solution to the conflict between nginx and backend port

question: When developing the Alice management sy...

Example of how to mosaic an image using js

This article mainly introduces an example of how ...

Linux Centos8 Create CA Certificate Tutorial

Install Required Files Yum install openssl-* -y C...

Detailed explanation of Linux lsof command usage

lsof (list open files) is a tool to view files op...

Detailed introduction to deploying k8s cluster on centos7 system

Table of contents 1 Version and planning 1.1 Vers...

Robots.txt detailed introduction

Robots.txt is a plain text file in which website ...