[JS : CLEAN CODE] 변수

이인송·2021년 4월 10일
0
post-thumbnail

🧐 들어가기

변수를 이름 짓는건 꽤나 많은 창의성을 요구한다
Clean Code 강의에서 나오는 변수 네이밍할 때 사용될 TIP 을 정리해보자

의미있고 발음하기 쉬운 변수 이름을 사용하세요

안좋은 예:

const yyyymmdstr = moment().format('YYYY/MM/DD');

좋은 예:

const currentDate = moment().format('YYYY/MM/DD');

동일한 유형의 변수에 동일한 어휘를 사용하세요

안좋은 예:

getUserInfo();
getClientData();
getCustomerRecord();

좋은 예:

getUser();

검색가능한 이름을 사용하세요

우리는 작성할 코드보다 읽을 코드가 더 많습니다.
그렇기 때문에 코드를 읽기 쉽고 검색 가능하게 작성해야 합니다.
그렇지 않으면 여러분의 코드를 이해하려고 하는 사람들에게 큰 어려움을 줍니다.
검색가능한 이름으로 만드세요

안좋은 예:

// 대체 86400000 무엇을 의미하는 걸까요?
setTimeout(blastOff, 86400000);

좋은 예:

// 대문자로 `const` 전역 변수를 선언하세요
const MILLISECONDS_IN_A_DAY = 86400000;
setTimeout(blastOff, MILLISECONDS_IN_A_DAY);

의도를 나타내는 변수들을 사용하세요

안좋은 예:

const address = 'One Infinite Loop, Cupertino 95014';
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
saveCityZipCode(address.match(cityZipCodeRegex)[1], address.match(cityZipCodeRegex)[2]);

좋은 예:

const address = 'One Infinite Loop, Cupertino 95014';
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
const [city, zipCode] = address.match(cityZipCodeRegex) || [];
saveCityZipCode(city, zipCode);

자신만 알아볼 수 있는 작명을 피하세요

안좋은 예:

const locations = ['서울', '인천', '수원'];
locations.forEach(l => {
  doStuff();
  doSomeOtherStuff();
  // ...
  // ...
  // ...
  // 잠깐, `l`은 또 뭘까요?
  dispatch(l);
});

좋은 예:

const locations = ['서울', '인천', '수원'];
locations.forEach(location => {
  doStuff();
  doSomeOtherStuff();
  // ...
  // ...
  // ...
  dispatch(location);
});

문맥상 필요없는 것들을 쓰지 마세요

안좋은 예:

const Car = {
  carMake: 'BMW',
  carModel: 'M3',
  carColor: '파란색'
};

function paintCar(car) {
  car.carColor = '빨간색';
}

좋은 예:

const Car = {
  make: 'BMW',
  model: 'M3',
  color: '파란색'
};

function paintCar(car) {
  car.color = '빨간색';
}

기본 매개변수가 short circuiting 트릭이나 조건문 보다 깔끔합니다

기본 매개변수는 종종 short circuiting 트릭보다 깔끔합니다.
기본 매개변수는 매개변수가 undefined일때만 적용됩니다.
'', "", false, null, 0, NaN 같은 falsy한 값들은 기본 매개변수가 적용되지 않습니다.

안좋은 예:

function createMicrobrewery(name) {
  const breweryName = name || 'Hipster Brew Co.';
  // ...
}

좋은 예:

function createMicrobrewery(name = 'Hipster Brew Co.') {
  // ...
}
profile
프론트 엔드와 심리학을 공부하는 대학생입니다 :)

0개의 댓글