maintainable code

What is maintainable code

1. Comprehensibility (others can take over the code and understand its intent and general approach without the need for a full explanation from the original developer)
 2. Intuitive (what's in the code can be understood at a glance, no matter how complicated its operation is) )
 3. Adaptability (the code is written in a way that data changes do not require complete rewriting)
 4. Extensibility (in the code architecture, it has been considered that the core functions can be expanded in the future)
 5. Debuggable Sexuality (when something goes wrong, the code can give you enough information to pinpoint the problem as directly as possible)

 


Code conventions
1. Readability

a. Functions and Methods - Each function or method should contain a comment describing its purpose and possible algorithm used to accomplish the task. It is also very important to state prior assumptions, such as parameter representation, whether the function has a return value (since this cannot be inferred from the function definition)
b. Large blocks of code - multiple lines of code for a single task should be preceded by a comment describing the task
c. Complex Algorithms - If a problem is solved in a unique way, explain in the comments how you did it.
d. Hack - Because of browser differences, js code generally contains some hacks. Don't assume that other people looking at the code understand the browser issues the hack is meant to deal with, put this information in a comment.

2. Variable and function naming
Since many js developers start out as hobbyists, there is a tendency to use meaningless names, such as foo, bar, dosomething. Professional js developers must overcome these vices to create maintainable code.

a. The variable name should be a noun such as car or person
b. The function name should start with a verb, such as getName(). Functions that return boolean values ​​generally start with is, such as isEnable();
c. Both variables and functions should use logical names, don't worry about the length. Length issues can be alleviated by post-processing and compression

3. Variable type transparency
Since variables are loosely typed in js, it is easy to forget the data type that the variable should contain. When initializing, use single-line comments on each line

var found = false ; // boolean 
var count = -1; // number 
var name = ''; // string 
var person = null ; // object

 


Loose
Coupling When one part of an application is overly dependent on another, the code is too tightly coupled and difficult to maintain. A typical problem is that an object directly references another object, and modifying one requires modifying the other.
Tightly coupled software is difficult to maintain and requires frequent rewriting.
1. Decouple HTML/JavaScript, html and javascript are too tightly coupled together
a, write directly in html to js

<script type='text/javascript'>
    document.write('hello world');
</script>
<input type='button' value='click me' onclick='doSomething()'/>

In this example, the button may have been pressed before the doSomething() function was available, raising a js error. Maintainability is compromised because any changes to button behavior touch both html and js.
And these should only be done in js

b, js contains html

function inserMessage(msg){
    var container = document.getElementById('container');
    container.innerHTML = '<div class="msg"><p class="post">'+msg+'</p><p>latest message above</p></div>'
}

Avoid creating a lot of html in js. Again, keep the layers separate so it's easy to identify the source of the error. When using the above example, there is a page layout issue, possibly related to the dynamically created html not being
properly formatted. However, locating this error is very difficult because you might normally look at the source code of the page to find that annoying piece of html, but not be able to find it because it is dynamically generated. Changes to data or layout
would also require changes to the js, indicating that the two layers are too tightly coupled.
It is recommended that when js is used to insert data, try not to insert tags directly. Generally, you can directly include and hide the markup in the page, and then after the entire page is rendered, you can use js to display the markup

2. Decoupling CSS/javascript
a and embedding CSS in js

element.style.color = 'red';
element.style.backgroundColor = 'blue';

Since the css is responsible for the display of the page, any problems with the display should be resolved by just looking in the css folder. However, when js is used to change some styles, such as colors, there is a second place that may have changed and
must be checked. The result is that js is also responsible for the display of the page to some extent and is tightly coupled with css. If the stylesheet needs to be changed in the future, both the css and js files may need to be modified. This creates a maintenance
nightmare for developers.
It is recommended that modern web applications often use js to change styles, so although it is impossible to completely decouple css and js, it can still make the coupling looser

element.className='edit';

By modifying only the CSS class of an element, you can keep most of the style information strictly in the CSS. js can change the style class, but it does not directly affect the style of the element.
b. Embed js in css (appears only in ie)

div{
    width:expression(document.body.offsetWidth - 10 + 'px');
}

Good hierarchy is very important. The only source of display problems should be css, and the only source of behavioral problems should be js. Keeping loose coupling between these layers makes the entire application easier to maintain.

 

Programming practice
1. Respect object ownership

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

If someone expects a function called stopEvent() to cancel the default behavior of an event, but you modify it, and it does what it was supposed to do, and then appends another event handler, there's bound to be a problem .
Other developers will think that the function is still executed the way it is, so their usage will be wrong and potentially harmful because they don't know there are side effects.

2. Avoid global variables

var name = 'Nicholas';
function sayName(){
    alert(name);
}

This code contains two globals: the variable name and the function sayName(). It is actually possible to create an object containing both
eg:

var MyApplication = {
    name:'Nicholas',
    sayName:function(){
        alert(this.name);
    }
}

This rewritten code introduces a single global object MyApplication.name and sayName() are attached to it. Doing this removes some of the problems that existed in the previous piece of 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 determined by MyApplication's code.

3. Avoid comparing with null

function sortArray(values){
    if(values != null){ //避免
        values.sort(comparator)
    }
}

The purpose of this function is to sort only one array based on the given comparison. For the function to execute correctly, the values ​​parameter must be an array, but the if statement here only checks if the values ​​are null. There are other values ​​that can be passed through the if statement, including
strings, numbers, and they will cause the function to throw an error.

function sortArray(values){
    if(Array.isArray(values)){ //推荐
        values.sort(comparator)
    }
}

If you see code that compares to null, try using the following techniques to replace
if the value should be a reference type, use the instanceof operator to check its constructor;
if the value should be a primitive type, use typeof to check its type;
if you want the object to contain For a specific method name, use the typeof operator to ensure that the method with the specified name exists on the object.

4. Use constants

function validate(value){
    if(!value){
    alert('Invalid value!');
        location.href='/errors/invalid.php';
    }
}

There are two pieces of data in this function: the piece of information to be displayed to the user and the url. Strings displayed on the user interface should be extracted in a way that allows for language internationalization, and URLs should also be extracted because of their
tendency to change as the application grows.
eg:

var const = {
    INVALID_VALUE_MSG:'Invalid value!',
    INVALID_VALUE_URL:'/errors/invalid.php'
}
function validate(value){
    if(!value){
    alert(Constans.INVALID_VALUE_MSG);
        location.href=Constans.INVALID_VALUE_URL;
    }
}

These settings allow data to be changed without touching the function that uses it.

Duplicate Values ​​- Any value that is used in multiple places should be extracted as a constant. This limits errors caused when one value changes while the other does not. This also includes the css class name.
User interface strings - any strings used to display to the user should be extracted to facilitate internationalization
URLs - In a web application, the location of resources can be easily changed, so it is recommended to use a common place to store all URLs.
Any value that may change - whenever you use a literal, you have to ask yourself if the value will change in the future. If it is, then the value should be extracted as a constant

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324761018&siteId=291194637