Write elegant quality code, should be consistent: specification, naming, comments, code elegant
If this is implemented and a reasonable code review is done, then it won’t be possible for someone to take over, or after a period of time, to suddenly shout out who wrote the code that sucks, check the log, no way, how can I write it myself?
specification
Prettier, ESLint, stylelint, Prettier, ESLint, stylelint, Prettier, ESLint, stylelint, Prettier, ESLint, stylelint, Prettier, ESLint, stylelint, Prettier, ESLint, stylelint, Prettier, ESLint, Prettier Some have no semicolons;
/ / eslint unity
arrayUnique (array) {
if (array && array.length) {
return [...new Set(... array)] } }// Don't have multiple styles, such as this one
arrayUnique(array)
if(array && array.length)
return [...new Set(... array)] } }/ / this
arrayUnique(array)
if(array && array.length)
return [...new Set(... array)] } }/ / this
arrayUnique(array) {
if(array&&array.length)
return [...new Set(...array)];
}
}
Copy the code
With a uniform style, reading code doesn’t look messy.
Unified automatic formatting, the worst thing that can happen is that your IDE will automatically format, and your colleagues don’t have it, or don’t press ESLint to grid, and the last commit will be all conflict, so it can’t proceed. Large teams recommend putting ESLint + Githooks directly, and don’t allow submission of code that doesn’t conform to the specification.
Attached are several major manufacturers of front-end specifications
Code tens of millions of lines, the first line of security; Front end is not standard, colleagues two lines of tears.
tencent
Tgideas.qq.com/doc/index.h…
jingdong
guide.aotu.io/index.html
baidu
github.com/ecomfe/spec
There are some specifications for HTML, CSS and JavaScript. If necessary, you can refer to them and make a specification for your team
named
JavaScript
Common naming conventions include Hungarian nomenclature, camel – hump nomenclature and PASCAL nomenclature
== Hungarian nomenclature == : Variable name = type + object description
- Array the array a
- Boolean Indicates the Boolean value B
- Float Indicates the floating point number L
- The function function fn
- Int integer I
- Object o
- Regular regular r
- String String s
// List data
let aListData = []
// Product data
let oProduct = {}
Copy the code
== Camelback: A variable or function name is a combination of one or more words that look like camel’s humps when the first word starts with a lowercase letter and all subsequent words begin with a capital letter
const myName = 'haha'
const arrayUnique = (array) = > {}
Copy the code
Pasca nomenclature ==: Is similar to the hump nomenclature, except that the first word is capitalized
const MyName = 'haha'
const ArrayUnique = (array) = > {}
Copy the code
css
Naming, 100 people have 100 kinds of naming, such as CSS, useful underlined -, underscore _, double slide line __, 10 people write a project, CSS various naming simply can not bear to look at, this is not obsessive compulsive disorder.
A common name, something like a header, is a header, something like this layout, I’m going to name it like this
<div class="header">
<div class="h-left">
<div class="h-l-back">return</div>
<div class="h-l-number">12</div>
</div>
<div class="h-center">The title</div>
<div class="h-right">
<div class="h-r-shopping">icon</div>
</div>
</div>
Copy the code
.header{}
.h-left{}
.h-l-back{}
Copy the code
Take the first letter of the parent element + the current content to form the calSS name, and take no more than three levels of the parent element, as in this case
<div class="main">
<div class="m-left">
<div class="m-l-nav">
<ul class="l-n-list">
<li class="n-l-item"></li>
</ul>
</div>
</div>
<div class="m-right"></div>
</div>
Copy the code
This makes CSS names less likely to clash, and everyone has a different naming style, such as BEM naming conventions.
What is BEM naming convention? BEM is short for block, Element, modifier, a front-end CSS naming methodology proposed by Yandex team.
annotation
Reasonable comments, why to say reasonable comments, lucky to see a code, 200 lines of code 100 lines of comments, curious is to write code or write articles?? Comments should help us understand the purpose of a function so that we can use it quickly without having to look at the logic and code of the function.
Self-explanatory code, try not to write comments
// Get the product data cache for the current page rendering
Storge.get('productData')
// Set the product list data, jump to the product list page need to use
Storge.get('productListData', productListData)
// Delete the current login data, clear and exit
Storge.remove('loginState')
/** * Check whether two values are equal ** Note: ** This method supports comparison of Arrays, array Buffers, Booleans, Date objects, error objects, maps, * numbers, Object objects, regexes, Sets, strings, symbols, and typed arrays. Object values compare their own properties, * excluding inherited and enumerable properties. Functions and DOM node comparisons are not supported. *@param value
* @param other* /
static isEqual(value, other) {
return isEqual(value, other)
}
Copy the code
Some difficult to explain code, or write comments, or you may come back after a period of time, you can not understand
/ * * *@name Path The path must be iconUrlPrefix + year (2020) + time prefix + suffix (if this rule is not used, the request will fail) */
var suffix = imageUrl.split('. ');
var type = suffix ? suffix[suffix.length - 1] : ' ';
var list = [{
token: res.token,
key: res.key,
path: "/" + res.iconUrlPrefix + new Date().toLocaleDateString().split("/") [0] + '/' + new Date().getTime() + ' ' + '. ' + type,
provider: 'FASTDFS',}]Copy the code
In conclusion, the code can be self-explanatory, try to explain the intent of the code through the context, function naming, variable naming, logic complexity in the explanation through comments == naming is more important than writing comments ==
All that is left is how to write clean, readable, and high-quality code
Improve code quality
Function SRP (single function)
== Scene == : Click Add to shopping cart. If you have not logged in, you need to jump to login and add to shopping cart
// Whether to log in
export async function isLogin () {
const token = Storage.get('token')
const v = token.match(/ # #. + (# #)? /g) [0];
if (v.startsWith('##ANONYMOUS')) {
return Promise.resolve(true)}return Promise.reject(new Error('Current state not logged in'))}// Add to cart
function addCart() {
isLogin().then(() = > {
// Add shopping cart logic operations. })}Copy the code
At this time there is a demand, need to take the current user membership level, generally there is already a code to judge the current user identity, add a transfer parameter, modify
/ * * * *@export
* @param {*} IsStatus Returns identity status (true returns identity) (false) Does not return *@returns* /
export async function isLogin (isStatus) {
const token = Storage.get('token')
const v = token.match(/ # #. + (# #)? /g) [0];
if(isStatus){
if (v.startsWith('##ANONYMOUS')) {
return Promise.resolve('VIP0')}if (v.startsWith('##VIP1')) {
return Promise.resolve('VIP1')}if (v.startsWith('##VIP2')) {
return Promise.resolve('VIP2')}}else {
if (v.startsWith('##ANONYMOUS')) {
return Promise.reject(new Error('Current state not logged in'))}return Promise.resolve(true)}}// Get the current user level
const level = await isLogin(true)
Copy the code
At this time should follow the single principle, do not mix multiple functions in a function, or later this function will only be bigger and bigger, more and more bloated, naming has not been a good explanation of the function function
// Get the current user level
export function getLevel() {
const token = Storage.get('token')
const v = token.match(/ # #. + (# #)? /g) [0];
if (v.startsWith('##VIP1')) {
return 'VIP1'
}
if (v.startsWith('##VIP2')) {
return 'VIP2'
}
return 'VIP0'
}
// Get the current user level
const level = getLevel()
Copy the code
Let functions always do one thing, one function, regardless of how many functions a function has.
The dictionary
== scenario == : The interface returns data of type INTEGER, Decimal, String, date, dateTime, which we need to display as integer, decimal, string, date, date, and time. Pick up the keyboard and type immediately
let typeStatus = ' '
switch (type) {
case 'integer':
typeStatus = 'integer'
break;
case 'decimal':
typeStatus = 'decimal'
break;
case 'string':
typeStatus = 'String'
break;
case 'date':
typeStatus = 'date'
break;
case 'dateTime':
typeStatus = 'Date and time'
break;
default:
typeStatus = ' '
}
Copy the code
At this point, use a dictionary to make your code elegant and not redundant
const typeDictionary = {
'integer': 'integer'.'decimal': 'decimal'.'string': 'String'.'date': 'date'.'dateTime': 'Date and time'
}
let typeStatus = typeDictionary[type] || ' ';
Copy the code
Does the code look clean and clear?
Active suspension
== Scenario == : Specifies whether to enter the user name and password in the authentication form
formSubmit(data) {
if(! data.name) { Toast('Name please')}else if(! data.password) { Toast('Please fill in your password')}else {
// Form submission logic. }}Copy the code
There is no problem with the above method, but the layers of ifelse seem to make the logic not very clear. The core of the business is at the bottom. Let’s optimize it to make the code quality better
formSubmit(data) {
if(! data.name) { Toast('Name please')
return
}
if(! data.password) { Toast('Please fill in your password')
return
}
// Form submission logic. }Copy the code
This is much better than the ifelse layer above, both in terms of conditional judgment and readability.
Use default values
createADirectory(name) {
const breweryName = name || 'directoryName';
// ...
}
Copy the code
Deconstruct the assignment, readable at a glance
createADirectory(name = 'directoryName') {
// ...
}
Copy the code
Transmission and control
== Scenario == : Encapsulates an Ajax function
function request(url, type, data, header) {
const sType = type || 'get';
const oData = data || {};
const oheader = type || {
'Content-Type': 'application/json; charset=utf8'
};
// Perform the encapsulated AXIOS request operation. }Copy the code
Function arguments should be limited to two. If more than two arguments are used, destruct syntax is used, regardless of the order of the arguments. This is better for both readability and performance
function request({
url = ' ',
type = 'get',
data = {},
header = {
'Content-Type': 'application/json; charset=utf8'}} = {}) {
// Perform the encapsulated AXIOS request operation. }Copy the code
As for whether to use let or const
- readability
- consistency
- scalability
After writing introspection, it may be because of time factors or schedule reasons, write the code function is no problem, back to the code quality bloated, can not bear to look at, need to improve, so that the way of programming, is a process of optimization, habit is getting better and better.