<clean-code-javascript>读书笔记之变量

113 阅读1分钟

一.变量

  1. Use meaningful and pronounceable variable names(使用有意义且能发音的变量名)
// bad
const date = moment().format('YYYY/MM/DD');

//good
const currentDate = moment().format('YYYY/MM/DD');
  1. Use the same vocabulary for the same type of variable(对于同一类型的变量使用相同的词汇表)
// bad
getUserInfo();
getClientData();
getCustomerRecord();

// good
getUser()

3.Use searchable names(使用可搜索的名字)

// bad
setTimeout(blastOff, 864000000);

// good
const MILLISECONDS_IN_A_DAY = 864000000;
setTimeout(blastOff, MILLISECONDS_IN_A_DAY)
  1. Use explanatory variables(使用解释变量)
// bad
const address = "One Infinite Loop, Cupertino 95014";
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
saveCityZipCode(
    address.match(cityZipCodeRegex)[1],
    address.match(cityZipCodeRegex)[2]
);

// good
const address = "One Infinite Loop, Cupertino 95014";
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
const [_, city, zipCode] = address.match(cityZipCodeRegex) || [];
saveCityZipCode(city, zipCode);
  1. Avoid Mental Mapping(Explicit is better than implicit)
// bad
const locations = ['Austin', 'New York', 'SanFrancisco'];
locations.forEach(l => {
    doStuff();
    doSomeOtherStuff();
    //...
    dispatch(l)
})

// good
const locations = ['Austin', 'New York', 'SanFrancisco'];
locations.forEach(location => {
    doStuff();
    doSomeOtherStuff();
    //...
    dispatch(location)
})
  1. Don't add unneeded context(不要添加不需要的上下文;if your class/object name tells you something, don't repeat that in your variable name.)
// bad
const Car = {
    carMake: 'Honda',
    carModel: "Accord",
    carColor: "Blue"
}

function paintCar(car) {
    car.carColor = 'Red'
}

// good
const Car = {
    make: "Honda",
    model: "Accord",
    color: "Blue"
}

function paintCar(car) {
    car.color = 'Red'
}
  1. Use default arguments instead of short circuiting or conditionals(使用默认参数替代短路或者条件语句)
// bad
function createMicrobrewery(name) {
    const breweryName = name || 'Hipster Brew Co.';
    //...
}

// good
function createMicrobrewery(name="Hipster Brew Co."){
    //...
}