This is the fourth day of my participation in the More text Challenge. For details, see more text Challenge
preface
Let me start with a real story that I’ve personally encountered at a previous company.
Sunny morning, everybody is in quiet of knock code, suddenly of some grumpy full stack big J shout: this excrescous same code is who write? This is what I’ve been looking for! Everyone looked at each other because they didn’t know if he was talking about front-end code or back-end code, and they weren’t sure if they had written it. After all, who can say they’ve never written shit? At this time, the project manager said: look at the Git submission record, find out and invite everyone to drink milk tea. Big J say: looking for. After a long time, big J did not say whose code, the project manager asked: found it? Big J said slowly: Yes, I wrote it myself a year ago…
Code is not standard, look back two lines of tears!
I’m sure you’ve come across all kinds of amazing code:
- The name depends on the mood, sometimes pinyin, sometimes letters, even sometimes 1234.
- Obviously 1 line of code can be done, because the foundation is poor, write 20 lines, but also think they are quite cattle.
- A function to handle n things, often dozens of lines, or even hundreds of lines.
- Never annotate, and complain that others never annotate. (This is really not me)
- …
There are many strange questions like these, and the list will be endless tomorrow.
So today, Big Ice has broken down these issues into 3 categories and 15 subcategories of front-end code specifications, which hopefully will be helpful to your development process.
Named article
In all the specifications, naming can be said to be the most important, a good naming habit makes the code look clear structure, data search is quick and convenient, bad naming habit makes people confused, can not find the north and south, accidentally into the confusion of the mire of the namer can not get rid of.
The very basic requirements for naming are:
The name word can be accurately described, avoid difficult to understand abbreviations, characters without meaning, do not redundant, as short as possible. The name word can be accurately described, avoid difficult to understand abbreviations, characters without meaning, do not redundant, as short as possible. The name word can be accurately described, avoid difficult to understand abbreviations, characters without meaning, do not redundant, as short as possible.
Name variables, constants, properties and functions
- Variable naming: Uniform specification: Little hump nomenclature: There are no hyphens between words, the first letter is lowercase, and the first letter of subsequent words is uppercase. Note the type of the variable. For example, Boolean values can be named isXXX, hasXXX, canXXX, etc. Values of the Array type can be named xxxList or xxxArray. Values of type Object can be named in xxxObj mode. Such as:
// bad
let a = [] // The semantics are not clear
let dc = [] // This is not a common abbreviation
let bookData = [] // Book data, but don't know what type
// good
let isBook = true // This is the Boolean type of the book
let bookList = [] // This is an Array of books
let studentObj = {} // This is a student's Object
Copy the code
- Constant naming: Uniform specification: uppercase letter + underscore character + uppercase letter. Such as: BASE_URL
// bad
const baseUrl = "http://localhost" // When called elsewhere, it is the same as a constant, and there is no way to change it
// good
const BASE_URL = "http://localhost" // It is obvious that this is a constant
Copy the code
- Attribute naming: Uniform specification: Little hump nomenclature: There are no hyphens between words, the first letter is lowercase, and the first letter of subsequent words is uppercase. Such as:
// bad
let studentObj={
studyName: "Ma Dongmei"
}
/* * studyName = studentObj; So I don't have to write studyName. * * /
// good
let studentObj={
name: "Ma Dongmei"
}
Copy the code
- Function naming: Uniform specification: Little hump nomenclature: there is no hyphen between words, the first letter is lowercase, and the first letter of subsequent words is uppercase. Such as:
// This function is used to retrieve a list of students
function getStudentList(){... }// This function is used to jump to the page
function jumpPage(){... }Copy the code
Name the current item within the loop (avoid context-dependent naming)
- Uniform specification: named according to the object in the current loop list.
// bad
studentList.forEach((item) = >{...// something.let list = item.books.map((e= >{...// something. }))...// something. })/* * Item, e, and studentList look unrelated to each other. When the logic inside the forEach is complicated and needs to be changed, many people will use item, value, e, and so on to represent the current item in the loop. The readability of such names becomes very poor when the logical complexity within the forEach makes the context too long. * You may also want to scroll up to see what item and e mean. We need a clear variable name. * This way, when maintaining code, we can quickly understand what the variable represents, rather than having to look through the context of complex logic. * /
// good
studentList.forEach((student) = >{...// something.let list = student.bookList.map((book= >{...// something. }))...// something. })Copy the code
Folder name
- Project folder: Lowercase letters + hyphens + lowercase letters. Such as:
vue-element-admin // As the main folder of projects, you can know what projects are at a glance
Copy the code
- Folders in views or Pages: Lowercase letters, hyphens, and lowercase letters. Such as:
error-page // As a folder of pages, the name should be accurate and clear, at a glance can know what page
Copy the code
- Folders within Components: Big hump Nomenclature: There are no hyphens between words and the first letter should be capitalized. Such as:
HeaderSearch // As a folder for storing components, the big hump name makes it distinguishable from other folders and easier to understand
Copy the code
CSS, SCSS, less file name
- Unified specification: Lowercase letters, hyphens, and lowercase letters. Such as:
element-ui.scss // The CSS file also needs a brief description of the word, and the scope of the file is known by its name
element-ui.less
element-ui.css
Copy the code
Js file naming
- Unified specification: Lowercase letters, hyphens, and lowercase letters. Such as:
drag-dialog.js // js files should also be clear and concise words, through the name can know its general function
Copy the code
Vue File name
- Vue files in SRC and Components: Big hump Nomenclature: There are no hyphens between words and the first letter must be capitulated. Such as:
/** * Import files and component files. The big hump name makes it distinguishable from other folders and easier to understand. * The same component class file should be spelled out, and the name will tell you what it does */
SwitchRoles.vue
Copy the code
- Vue files in other folders: Lowercase letters + hyphens + lowercase letters. Such as:
auth-redirect.vue // Make sure the name of the component is clear
Copy the code
Img file name
- If the icon is an icon, it should be reflected in the name.
- Uniform specifications: Lowercase letters + underscores (_) + lowercase letters Such as:
icon_up_arrow.png // You can see the "icon" at a glance
bg_header.png // This is a background image of the head
Copy the code
Naming a JSON file
- Uniform specifications: Lowercase letters + underscores (_) + lowercase letters Such as:
china_city.json // Json files for Chinese cities
Copy the code
Other file names
- Uniform specifications: Lowercase letters + underscores (_) + lowercase letters Such as: deploy – docker. Sh
deploy-docker.sh // The words are concise and the semantics are clear
Copy the code
Function article
Parameter sets the default values
To set a default value for a parameter, there is no need to handle the unpassed value of the current parameter in the function. Avoid code redundancy, more readable. Such as:
// bad Code redundancy, increasing the number of reads
function getStudentList(currentPage, pageSize) {
currentPage = currentPage || 1
pageSize = pageSize || 10.// something. }// set the default value for good, one word: absolutely!
function getStudentList(currentPage = 1, pageSize = 10) {...// something. }Copy the code
The number of parameters is limited
If a function has more than five parameters, you may find it tiring to read. And the parameters are sequential, which means that when you call a function you need to match the parameters to the parameters, or you’ll get an unexpected error.
Therefore, it is best to keep the function parameters to 3. If more than 3 parameters are used, the function can be directly combined into an object, so that the function can be called with clear understanding of the meaning of each parameter. Such as:
// Too many bad parameters, code redundancy, increased reading
function getStudentList(currentPage = 1, pageSize = 10, search = "", startTime = "", endTime = "") {
currentPage = currentPage || 1
pageSize = pageSize || 10.// something. }// good merges the parameters, no need to remember the order, one word: absolutely!
let searchData = {
currentPage: 1.pageSize: 10.search: "".startTime: "".endTime: ""
}
function getStudentList(searchData) {...// something. }Copy the code
Function limitation
Want to feel the fear of being ruled by a function with tens or even hundreds of lines? It’s just sitting there: Come on, get to know me. You don’t know how it works until you’ve been through it
A function should have only one function, and the right way to do this is to create functions that are easy to understand and maintain, but also to make people feel comfortable reading your code instead of scolding you. Such as
// bad
function init() {
axios.get('/studentList').then((success) = >{...// something. })...// something. axios.get('/bookList').then((success) = >{...// something. })}// good
function getStudentList() {
axios.get('/studentList').then((success) = >{...// something. })}function getBookList() {
axios.get('/bookList').then((success) = >{...// something. })}function init(){
getStudentList()
getBookList()
}
Copy the code
gemara
There are two kinds of people I hate most in my life: people who don’t annotate and people who make me annotate. I have to say that writing comments is a good habit, but it is increasingly rare for programmers to take them seriously.
So what’s something to note about comments?
Where comments are not necessary
Named semantically coded code does not have to be commented. If your name is standard, people will understand it without comments. Such as:
let studentList = ["Little,"."Abortion"."Xiao Ming"] // This is a list of students.
function getStudentList(){} // This is the way to get a list of students.
Copy the code
Single-line comments
Javascript uses a single line comment, either directly after the comment object or on a single line above the comment object. If there is a single line, it is best to insert a blank line before the comment so that the comment is at a distance from the above line and you can see that the comment is for the code below.
// bad
let sb = "j100" // What is this?
function getUCData(){} // What is this?
// good
let sb = "j100" // I don't know what you mean
// This function is used to get some data from UC
function getUCData(){}
Copy the code
Multiline comment
Use the / * *… */ as a multi-line comment. Contains descriptions, types and values that specify all parameters and return values. /* *@
// bad has no comment. You need to read through it to understand what the current function does
function addTips(text="No content", time=1500) {
let oldTip = document.querySelector(".window-new-tips")
oldTip? document.body.removeChild(oldTip) : ' '
let tip = document.createElement("p")
tip.classList.add("window-new-tips")
tip.innerText = text
tip.style.cssText = "z-index: 9; position:fixed; top:40%; left:50%; transform: translate(-50%,-50%); Opacity: 0.6; background: #000000; Border - the radius: 0.06 rem; font-size: 14px; color: #FFFFFF; text-align: center; Padding: 0.1 rem 0.35 rem;"
document.body.appendChild(tip)
setTimeout(() = > {
document.body.contains(tip)? document.body.removeChild(tip) : ' '
}, time)
}
// You don't need to fully understand the content of the function to know what it does
/ * * *@param Text: indicates the displayed text, and time: indicates the duration of the display *@return No *@example FormatNumber (" no more ",1500); *@description You can customize the display text and display duration */
function addTips(text="No content", time=1500) {
let oldTip = document.querySelector(".window-new-tips")
oldTip? document.body.removeChild(oldTip) : ' '
let tip = document.createElement("p")
tip.classList.add("window-new-tips")
tip.innerText = text
tip.style.cssText = "z-index: 9; position:fixed; top:40%; left:50%; transform: translate(-50%,-50%); Opacity: 0.6; background: #000000; Border - the radius: 0.06 rem; font-size: 14px; color: #FFFFFF; text-align: center; Padding: 0.1 rem 0.35 rem;"
document.body.appendChild(tip)
setTimeout(() = > {
document.body.contains(tip)? document.body.removeChild(tip) : ' '
}, time)
}
Copy the code
Afterword.
Front-end development specifications are destined to be around the open block, remember before a colleague always like to format code, all he changed the file, even if only 1 line, the whole file will be formatted by him. Of course, git commit is also part of the front-end development specification, and some of the specifications listed today are not quite comprehensive, but just part of the ice sheet. There is no right or wrong, after all, there is no right or wrong norm, as long as everyone on the team adheres to it is beneficial.
The purpose of this article is to provide an idea for front-end projects and code optimization to reduce the time and labor costs of code maintenance. If it helps you, just like it, and if there are mistakes, you are welcome to point them out. Thanks for reading.
PS: today is the fourth day to participate in the nuggets more text challenge, I did not save the manuscript, today’s blog took half a day, again teasing myself how slow.
Although not many people see it, but also to their own drainage ~ more challenging article catalog is as follows:
- Flex layout container elements and project elements attributes
- 2021.06.02 how to play with CSS Gradient Background
- How to Use SVG to create Text Effects along Arbitrary Paths