I found that there was very little discussion among the front-end students about the great book of software engineering called “The Code Clean Way”, and some front-end students in the team didn’t even know this book for many years. Maybe there are too many front-end things to learn, plus the flexibility of JS itself, resulting in code cleanliness seems not so important. Value people, also often lack practice or do not know how to practice. This article summarizes some of my own experiences, as well as some blogs, and puts together a guide to JS/TS code. If you are interested, please refer to my other blog post: SOLID Principles and Practices – Nuggets (juejin. Cn)
The variable name
-
The team can define it internally, and appropriate variable names should make it easy to understand and maintain. Example:
CurrentDate over time TMP over meaningless named constants like S/A /b in all uppercaseCopy the code
-
Keep names consistent. For example, if the user is related, everyone starts with user, such as userInfo, userName, etc
-
Don’t use magic numbers use constants instead of magic numbers
-
Don’t use too much context for example
class User{ name:string } Copy the code
Better than
class User{ userName:string } Copy the code
-
Reduce useless variables like
return createUser(); const user = createUer(); return user; Copy the code
function
- A proper function name is the same as a variable name. A function name needs to intuitively explain what the function does. For example: getCurrentDay We can also use fixed prefixes such as:
- Sending service requests can be named requestXXX,
- Submit data like server can be named submitXXX,
- Functions that have no arguments but return values can be named getXXX,
- A function that creates a new object can be named createXX,
- Functions that take arguments but return no value can be named handlerXXX,
- Functions that take arguments and return values can be named processXXX,
- Functions that return Boolean values can be named isXXX/hasXXX,
- If you make changes to the input object, you can name it updateXXX,deleteXXX, etc.
- Appropriate parameter defaults
function createUser(name = "nobody") {
// ...
}
Copy the code
3. Don’t have too many arguments, otherwise you can consider splitting the function, or encapsulating the arguments. Such as
Function createUser(name = "nobody", age= "18",sex= "man",licenceId= "") {//... }Copy the code
Can be encapsulated as
Function createUser ({name = "nobody", the age = '18', sex = 'man', licenceId = '}) {/ /... } createUser({name = "congbai", age='28', sex='man', licenceId=''})Copy the code
Or we could split it into two
const user = createUserByName('congbai')
user.setAge(20)
user.setSex('man')
Copy the code
- Single responsibility
The difficulty here is how to define ‘responsibility’. For example, we can make ‘create user’ as one responsibility, or we can break it down into ‘Create user name, Set user age, set user gender’ three responsibilities. This depends on your business scenario. Six reference standards:
-
If there are more than 50 lines of code in a responsibility, you can definitely split out more responsibilities.
-
If a piece of logic is reused more than twice, it can be shared
-
If a piece of logic has no side effects, it can be removed
-
If there are too many judgment conditions, it can be split out
-
If /else internal logic, try to break it out
-
The map, reduce, foreach code snippets passed into the array can be split out
-
Multilayer nesting must be removed, up to two layers
-
If an argument passed inside a function is used as an if condition directly, then the if-related logic should be handled outside the function: for example:
Function createUser (sex= 'man') {if(sex==='man') {return createMan()} else{return createWoman()}} functin getUser(){ const sex= getSex(); return createUser(sex); }Copy the code
Can be changed to
functin getUser(){ const sex= getSex(); if(sex ==='man'){ return createMan() }esle{ return createWoman() } } Copy the code
-
Use es6’s deconstruction syntax to copy and assign values for example
user={ ... anotherUser, age:28 } allUser=[...oldUser,...newUser]Copy the code
-
Reduce the side effects of functions
- Avoid modifying any variables other than parameters
- If possible, try to return a new object rather than modifying the object in the argument.
Such as
function addUserToList(user,list){ user.age=19; list.push(user); Function addUserToList(user,list){return [...list,{...user,age:19}]}Copy the code
It is possible because of the loss of performance, so it should be measured.
-
Try to use functional programming such as arrays of foreach,filter, etc.
-
Use polymorphism and design patterns to reduce if/else judgments and reduce coupling.
See also SOLID principles and Practices – Nuggets (juejin. Cn) 9. Use Promise instead of the callback function
Class design
- Use get set accessors to modify properties whenever possible
- Use composition more than inheritance
- Don’t modify the prototype if you don’t have to
- The set accessor can return ‘this’ for chained calls
Such as
class User { setName(name){ this.name = name; return this; } setAge(age){ this.age = age return this; }} user.setname (' mytage ').setage (28)Copy the code
- The order of methods in a class is best arranged in some order. For example, if B is called from A, B should come after A, making it easier to read.
other
-
These principles are for reference, not for strict observance.
-
There is no beautiful code that can be written once and for all, and it needs to be fixed periodically according to these principles
-
Indentation, naming, and short coding are all guarantees of poetic beauty
-
Proper naming can effectively reduce the need for annotations, but annotations should be made where they are. When code is reviewed, there should be annotations for all the parts that others cannot understand.