역할이 둘 이상인 변수가 있다면 쪼개야한다.
여러 용도로 사용된 변수는 읽은 이에게 혼란을 주기 때문!
데이터 구조와 프로그램을 이해하기 위해서는 필드 이름이 중요하다.
레코드가 캡슐화되지 않았다면 캡슐화부터 진행하기
가변 데이터의 유효 범위를 좁혀 이슈를 방지해야한다.
bad case
get discountTotal(){
return this._discountedTotal
}
set discount(aNumber){
const old = this._discount
this._discount = aNumber
this._discountedTotal += old - aNumber
}
good case
get discountedTotal(){
return this._baseTotal - this._discount
}
set discount(aNumber){
this._discount = aNumber
}
bad case
class Product {
applyDiscount(arg) {
this._price.amount -= arg;
}
}
good case
class Product {
applyDiscount(arg) {
this._price = new Money(this._price.amount - arg, this._price.currency);
}
bad case
let customer = new Customer(customerData);
good case
let customer = customerRepository.get(customerData.id);
숫자 대신 상수를 정의하고 코드 자체가 뜻을 명확히 드러내는 것이 좋다.
매직 리터럴: 소스 코드에 등장하는 일반적인 리터럴 값
ex) 모든 사람이 9.800665 라는 숫자를 보고 "이 숫자가 표준 중력을 의미한다." 라는 것은 알 수 없다. 이 때, 9.800665는 매직 리터럴이 된다.
bad case
// 매직 리터럴
function potentialEnergy(mass,height) {
return mass * 9.81 * height;
}
// 상수 남용
const ONE = 1;
good case
const STANDART_GRAVITY = 9.81;
function potentialEnergy(mass,height) {
return mass * STANDART_GRAVITY * height;
}