[리팩터링 2판] 9. 데이터 조직화

Ash·2021년 12월 4일
0

9.1.변수 쪼개기

역할이 둘 이상인 변수가 있다면 쪼개야한다.
여러 용도로 사용된 변수는 읽은 이에게 혼란을 주기 때문!

9.2 필드 이름 바꾸기

데이터 구조와 프로그램을 이해하기 위해서는 필드 이름이 중요하다.
레코드가 캡슐화되지 않았다면 캡슐화부터 진행하기

9.3 파생 변수를 질의 함수로 바꾸기

가변 데이터의 유효 범위를 좁혀 이슈를 방지해야한다.
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
}

9.4 참조를 값으로 바꾸기

  1. 후보 클래스가 불변인지, 혹은 불변이 될 수 있는지 확인한다.
  2. 각각의 세터를 하나씩 제거한다.
  3. 값 객체의 필드들을 사용하는 동치성 비교 메소드를 만든다.

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);        
	}

9.5 값을 참조로 바꾸기

  1. 같은 부류에 속하는 객체를 보관할 수 있는 저장소를 만든다.
  2. 생성자에서 이 부류의 객체들 중 특정 객체를 정확히 찾아내는 방법이 있는지 확인한다.
  3. 객체의 생성자들을 수정하여 필요한 객체를 저장소에서 찾아내고, 하나를 수정할 때마다 테스트 한다.

bad case

let customer = new Customer(customerData);

good case

let customer = customerRepository.get(customerData.id);

9.6 매직 리터럴 바꾸기

숫자 대신 상수를 정의하고 코드 자체가 뜻을 명확히 드러내는 것이 좋다.
매직 리터럴: 소스 코드에 등장하는 일반적인 리터럴 값
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;
}

예제 소스코드
https://github.com/yeoj1n/JS-study/blob/master/refactoring-study/chapter09/%EB%8D%B0%EC%9D%B4%ED%84%B0%20%EC%A1%B0%EC%A7%81%ED%99%94.js

profile
기록남기기👩‍💻

0개의 댓글