I’m sure you’ve all worked on an old project, but what’s the code style? Probably most students will be unable to make fun of it. The author thinks that a code is good or bad, regardless of its implementation, at least its readability is guaranteed, can be considered as a good code. For those of you who are not aware of the benefits of readability code, you may often come across code that you wrote last week. Today you open the project and say, “Oh my God, did I write this 💩 code?”
The author’s code cleanliness is a bit serious, so usually write their own code also have higher requirements, at least in the readability is more able to ensure. Here are some tips for code readability and brevity.
named
I believe that most of the jokes are about the naming of variables, which leads to the emergence of magic tools like CodeIf to assist in the declaration of variable names. Therefore, how to make good naming in normal projects?
In fact, most variables don’t change after assignment (reassignment), so I prefer const to let. There is no way to avoid using let after multiple assignments.
Constants should all be named
// Bad
static({
maxAge: 28800000.// what ???
});
// Good
const EIGHT_HOURS_IN_MILLISECOND = 28800000;
// or
const EIGHT_HOURS_IN_MILLISECOND = 8 * 60 * 60 * 1000;
static({
maxAge: EIGHT_HOURS_IN_MILLISECOND,
});
// Bad
$(document).on('keydown', event => {
// What is 27?
if(event.keyCode === 27) {
// do something ...}});// Good
$(document).on('keydown', event => {
const KEY_ESC = 27;
if(event.keyCode === KEY_ESC) {
// do something ...}});Copy the code
Meaningful naming
// Bad
const n = 'Big chestnut';
const a = 18;
// Good
const name = 'Big chestnut';
const age = 18;
Copy the code
Reduce naming redundancy
// Bad
const favoriteList = [];
const getCurrentUserData = (a)= > {};
// Good
const favorites = [];
const getCurrentUser = (a)= > {};
Copy the code
As the name implies
The function name alone should tell you what the function is.
// Bad
function fetchAtls() {}
// Good
function fetchArticles() {}
// or
function getArticles() {}
Copy the code
function
Simplify the code
Simplify code with ternary operators and ES6+ syntax
// Bad
$('.js-button').on('click'.function() {
var name = '开始';
if ($(this).hasClass('again')) {
name = 'Play it again';
}
app.track('button', name);
});
// Good
$('.js-button').on('click'.function() {
const again = $(this).hasClass('again');
app.track(again ? 'Play it again' : '开始');
});
// Bad
const celebrationDayChange = isSameDay= > {
if (isSameDay) {
$dateSelect.addClass('hide');
} else {
$dateSelect.removeClass('hide'); }};// Good
const celebrationDayChange = isSameDay= > {
const action = isSameDay ? 'addClass' : 'removeClass';
$dateSelect[action]('hide');
};
Copy the code
Function parameters
Keep the parameters of the function as short as possible. If there are more than three parameters, it is recommended to directly change them into objects:
// Bad
function publish(title, author, except, content) {}
// You must know the parameter location information
publish('title'.'Big chestnut'.'an excellent article'.'This is content.');
// Good
function publish({title, author, except, content}) {}
publish({
title: 'title'.author: 'Big chestnut'.except: 'an excellent article'.content: 'This is content.'});Copy the code
Sets the default properties of the object
// Bad
const options = {
name: 'Big chestnut'.logo: 'Logo.png'.theme: 'dark'};function createApp(options = {}) {
options.name = options.name || 'App';
options.logo = options.logo || 'Logo.png';
options.theme = options.theme || 'light';
}
// Good
function createApp(options = {}) {
options = Object.assign({
name: 'App'.logo: 'Logo.png'.theme: 'light',
}, options);
}
Copy the code
Parameter Default Value
// Bad
function App(name) {
name = name || 'App';
// ...
}
// Good
function App(name = 'App') {
// ...
}
Copy the code
Functional style
// Bad
function querify(object = {}) {
const keys = Object.keys(object);
let result = ' ';
for(let i = 0; i < keys.length; i++) {
result += ` &${keys[i]}=${object[keys[i]]}`;
}
result = result.slice(1);
return result;
}
// Good
function querify(object = {}) {
const keys = Object.keys(object);
const result = keys.reduce((prev, current) = > {
prev += ` &${current}=${object[current]}`;
return prev;
}, ' ').slice(1);
return result;
}
Copy the code
Encapsulate if judgment conditions
Here is a snippet of code from a PostCSS plugin that automatically adds width and height to background images:
// Bad if (/background[^:]*.*url[^;] +/gi.test(ruleString)) { const [originURL, URL] = getImageURL(ruleString); / /... } // Good const hasBackground = rule => /background[^:]*.*url[^;] +/gi.test(rule); if (hasBackground(ruleString)) { const [originURL, URL] = getImageURL(ruleString); / /... }Copy the code
Just do one thing
A function is the least reusable unit, So if a function does more than one thing, it is difficult to reuse the function.
// Bad
function notify(users) {
users.map(user= > {
const record = DB.find(user);
if(record.isActive()) { sendMessage(user); }}); }// Good
// judge activation only
function isActive(user) {
const record = DB.find(user);
return record.isActive();
}
function notify(users) {
users.filter(isActive).forEach(sendMessage);
}
Copy the code
Do not name functions with negative syntax
// Bad
const isNotSupport = (a)= > {};
const canNotUpdate = (a)= > {};
// Good
const isSupport = (a)= > {};
const canUpdate = (a)= > {};
Copy the code
Use ES6+ syntax
deconstruction
// Bad
const first = items[0];
const second = items[1];
const name = me.name;
const age = me.age;
// Good
const [first, second] = items;
const { name, age } = me;
// Bad
function App(options) {
track({
name: options.name,
version: options.version,
env: options.env,
});
}
// Good
// Destruct function arguments
function App({name, version, env}) {
track({
name: name,
version: version,
env: env,
});
}
// Best
function App({name, version, env}) {
// Use object shorthand
track({ name, version, env });
}
Copy the code
Template string
// Bad
const greeting = name= > 'Hello ' + name + '! ';
// Good
const greeting = name= > `Hello ${name}! `;
Copy the code
Arrow function
// Bad
function greeting(name) {
return `Hello ${name}! `;
}
// Good
const greeting = name= > `Hello ${name}! `;
Copy the code
Deprecate the callback function
// Bad
fetchCurrentUser((error, currentUser) = > {
if(error) throw Error;
fetchArticles(currentUser.id, (error, articles) => {
if(error) throw Error;
// articles here...
});
});
// Good
fetchCurrentUser
.then(currentUser= > currentUser.id)
.then(fetchArticles)
.then(articles= > {
// articles here...
})
.catch((a)= > {
throw Error;
});
// Best
try {
const currentUser = await fetchCurrentUser();
const articles = await fetchArticles(currentUser.id);
// articles here...
} catch() {
throw Error;
}
Copy the code
conclusion
Long, descriptive names are better than short, convoluted names, and better than long, descriptive comments. Good code is self-commented, and don’t worry about long variable names (they all look the same when compressed by packaging tools).
Code is written for people as well as for machines, so start writing readable and maintainable code now.
Finally, a friendly reminder of tens of thousands of lines of code, comment the first line. Programming is not standard, colleagues two lines of tears.