의도가 분명하게 이름을 지어라.
변수, 함수, 클래스 이름을 명시할 때 고려할 점
따로 주석이 필요하다면 의도를 분명히 드러낸 것이 아님
의도가 드러나는 이름을 사용하면 코드의 이해와 변경이 쉬워짐
const d; // 경과 시간(단위: 날짜)
❌ const elapsedTimeInDays;
const daysSinceCreation;
const daysSinceModification;
const fileAgeInDays;
function getThem() {
const list1 = [];
for (let i = 0; i < theList.length; i++) {
if (theList[i] === 4) {
list1.push(theList[i]);
}
}
return list1;
}
function getFlaggedCells() {
const flaggedCells = [];
for (let i = 0; i < gameBoard.length; i++) {
const cell = gameBoard[i];
if (cell[STATUS_VALUE] === FLAGGED) {
flaggedCells.push(gameBoard[i]);
}
}
return flaggedCells;
}
function getFlaggedCells() {
const flaggedCells = new CellList();
for (let i = 0; i < gameBoard.length; i++) {
const cell = gameBoard[i];
if (cell.isFlagged()) {
flaggedCells.add(gameBoard[i]);
}
}
return flaggedCells;
}
널리 쓰이는 으미가 있는 단어를 다른 의미로 사용하지 말 것
list와 같이 프로그래머에게 특수한 의미를 지니는 단어를 함부로 사용하지 말 것
if 여러 계정을 그룹으로 묶는 경우, 실제 List가 아닌 경우 accountList
❌
accountGroup
, bunchOfAccounts
... accounts
이름으로 그릇된 정보를 제공하는 최악의 예) 소문자 L or 대문자 O 변수
let a = 1;
if (O === l) a = O1;
else l = 01;
// ❌
let foo = (a1, b1) => {
for (let i = 0; i < a1.length; i++) {
a1[i] = b1[i];
console.log(a1[i]);
}
}
// ⭕️
let updateArray = (sourceArray, destinationArray) => {
for (let i = 0; i < sourceArray.length; i++) {
sourceArray[i] = destinationArray[i];
console.log(sourceArray[i]);
}
}
nameString
, ageVariable
moneyAmount
vs money
customerInfo
vs customer
accountData
vs account
theMessage
vs message
프로그래밍 == 사회활동
→ 원활한 의사소통을 위해 발음하기 쉬운 이름을 사용할 것// ❌
const yyyymmdd = new Date();
// ⭕️
const currentDate = new Date();
class DtaRcrd102 {
constructor(genymdhms, modymdhms) {
this.genymdhms = genymdhms;
this.modymdhms = modymdhms;
}
}
class Customer {
constructor(generationTimestamp, modificationTimestamp) {
this.generationTimestamp = generationTimestamp;
this.modificationTimestamp = modificationTimestamp;
}
}
// ❌
for (let j = 0; j < 34; j++) {
s += (t[j]*4)/5;
}
// ⭕️
let realDayPerIdealDay = 4;
const WORK_DAYS_PER_WEEK = 5;
let sum = 0;
for (let j = 0; j < NUMBER_OF_TASKS; j++) {
let realTaskDays = taskEstimate[j] * realDaysPerIdealDay;
let realTaskWeeks = (realTaskDays / WORK_DAYS_PER_WEEK);
sum += realTaskWeeks;
}
문제 해결에 집중하는 개발자에게 인코딩은 불필요한 정신적 부담
인코딩한 이름은 거의 발음하기 어려우며 오타가 생기기 쉬움
헝가리식 표기법
: 이름의 앞에 데이터 타입을 명시하는 것
이름 길이가 제한된 옛날에는 이 규칙을 위반할 수밖에 없었음
요즘의 ide는 컴파일 하지 않고도 타입 오류를 감지할 정도로 발전함
멤버 변수 접두어
멤버 변수에 m_이라는 접두어를 붙일 필요 X
클래스와 함수는 접두어가 필요 없을 정도로 작아야 함
멤버 변수를 다른색상으로 표시하거나 눈에 띄게 보여주는 ide를 사용해야 함
❌ 리스트
phoneNumber phoneString;
// ❌
class Part {
constructor(m_dsc) {
this.m_dsc = m_dsc; // 설명문자열, m_은 멤버 변수를 뜻함.
}
setName(name) {
m_dsc = name;
} // 예전에는 이렇게 썼음
}
// ⭕️
class Part {
constructor(description) {
this.description = description;
}
setDescription(description) {
this.description = description;
} // 이런 식으로 쓰는 것을 권장
}
ShapeFactoryImp
& CShapeFactory
>> IShapeFactory
whack()
대신 kill()
, eatMyShort()
대신 abort()
add()
insert()
또는 append()
가 적합대다수의 이름 : 의미가 불분명함
주소의 일부를 표현하는 변수의 경우
firstName
, lastName
, street
, houseNumber
, city
, state
...addrFirstName
, addrLastName
, addrStreet
, addrHouseNumber
, addrCity
, addrState
...function printGuessStatistics(candidate, count) {
let number;
let verb;
let pluralModifier;
if (count === 0) {
number = 'no';
verb = 'are';
pluralModifier = 's';
} else if (count === 1) {
number = '1';
verb = 'is';
pluralModifier = '';
} else {
number = count.toString();
verb = 'are';
pluralModifier = 's';
}
const guessMessage = `There ${verb} ${number} ${candidate}, ${pluralModifier}`;
console.log(guessMessage);
}
class GuessStatisticsMessage {
constructor(number, verb, pluralModifier) {
this.number = number;
this.verb = verb;
this.pluralModifier = pluralModifier;
}
make(candidate, count) {
this.createPluralDependentMessageParts(count);
const tmp = `There ${this.verb} ${this.number} ${candidate} ${
this.pluralModifier}`;
return tmp;
}
createPluralDependentMessageParts(count) {
if (count === 0) {
this.thereAreNoLetters();
} else if (count === 1) {
this.thereIsOneLetter();
} else {
this.thereAreManyLetters(count);
}
}
thereAreManyLetters(count) {
this.number = String(count);
this.verb = 'are';
this.pluralModifier = 's';
}
thereIsOneLetter() {
this.number = '1';
this.verb = 'is';
this.pluralModifier = '';
}
thereAreNoLetters() {
this.number = 'no';
this.verb = 'are';
this.pluralModifier = 's';
}
}