★★★★✰

The profile

Make the people reading your code happy!

Coding for an hour, naming for half an hour, what makes us so tangled? I think the biggest problem is the limitation of language, if we use Chinese naming, maybe it is not so difficult, accumulate more vocabulary, do better!

It may take some time at first, but stick with it and make your code prose.

1. Live up to your name

The name indicates the purpose, and if the name needs a comment to complement it, it’s not worthy of the name.

bad:

let d; // elapsed time in days
Copy the code

good:

let elapsedTimeInDays;
Copy the code

bad:

getList() {
	let list1 = []
	theList.forEach(item= > {
		if (item === 4) {
			list1.push(item)
		}
	})
	return list1
}
Copy the code

good:

const FLAGGED = 4 // Constant comments

getFlaggedCells() {
	let flaggedCells = []
	gameBoard.forEach((cell) = > {
		if (isFlagged(cell)) {
			flaggedCells.push(cell)
		}
	})
	return flaggedCells
}

isFlagged(cell) {
    return cell === FLAGGED
}
Copy the code

For code clarity, consider wrapping the cell once (ES6)

const FLAGGED = 4 // Constant comments
class Cell {
    constructor(positionNumber) {
        this.positionNumber = positionNumber
    }

    isFlagged() {
        return this.positionNumber === FLAGGED
    }
}
export default Cell
Copy the code

2. Avoid misdirection

bad

// An object or map named list is misleading
let accountList = {
	'name': 'wang'
}

// Take the width value and name it height
let boxHeight = dom.clientWidth
Copy the code

3. Make meaningful distinctions

bad 1

let student = 'wang'
// goodStudent is good when you want to declare "goodStudent", bad when you want to declare "goodStudent
// Change the initial letter from s to A
let atudent = 'li'
Copy the code

bad 2

// a1, a2 makes no sense
function(a1, a2(// This is betterfunction(target, source)
Copy the code

bad 3

// There is no difference in meaning between these names
let product
let productInfo
let productData

// A method like this is called without knowing which method to call
getActiveAccount()
getActiveAccounts()
getActiveAccountInfo()
Copy the code

4. Use pronounceable names

Humans are good at remembering and using words.

bad

// Generate date, year, month, day, hour, minute, second
const genymdhms = () = > {}

// This is better
const generateTimestamp
Copy the code

5. Use searchable names

The search function is often used in the development process. Think about the convenient name if you want to search where a variable is referenced.

bad

// Where 5 is not easy to search
findRelaxCompany(company) {
	company.workDays = 5
}

// This is better
const WORK_DAYS_PER_WEEK = 5
findRelaxCompany(company) {
	company.workDays = WORK_DAYS_PER_WEEK
}
Copy the code

6. Redundant prefixes and suffixes

bad

// Use the name to describe the type
let booleanIsBlack = true
let numberStudentCount = 100

// Unnecessary member prefixes
let student = {
	studentName: 'wang'.studentAge: 10
}
/ / or
let student = {
	attributeName: 'wang'.attributeAge: 10
}

// In module naming, the following name is also not good, do not need to add page prefix
--page
	|
	---pageHome
	|
	---pageLogin

// This is better
let student = {
	name: 'wang'.age: 10
}
Copy the code

7. Class and method naming

Class: noun or noun phrase.

Method: Verb or phrasal verb.

Don’t be clever and precise when naming. Humorous code words may not be understood.

Consistency 8.

Same types of concepts, same conventions, and always.

fetchUser getOrder retrieveUserFamily queryUserAddress

If the above methods all represent the scenario of retrieving data from the back-end interface, then the prefix should be uniform and should not be used arbitrarily between fetch, GET, Retrieve and Query.

The same

If generator and producer both represent generators, there should be a common naming scheme.

Consistency is of great benefit when using editor retrieval capabilities.

9. Use common domain names

Only programmers read your code, so use common names like computer terminology, algorithm names, schema names, and mathematical terminology.

Such as:

CDN – Content Delivery Network

RAM – Random Access Memory

10. Add context

Few names speak for themselves, so you need to place names with well-named classes, functions, or namespaces to give context to the reader. Adding a prefix to a name is a last resort if not convenient.

For example, the name “state” may not be clear by itself, but if you add “addrState”, you can know that it represents the address.

Or add a context object:

let address = {
	state: 'xx'.city: 'yy'
}
Copy the code

This article is based on Code Cleanliness by Robert C. Martin, translated by Han Lei.

Zhejiang Dahua Technology Co., Ltd.- Soft research – Smart City Product R&D Department Recruiting senior front end, welcome to contact, interested can send resume to [email protected], long-term effective

Previous post: Clean Code

Next: Three, functions