09. 데이터 조직화

전반적으로 적용하기 쉽지만 좋은 습관, 중요한 내용이라 생각

9.1 변수 쪼개기#

// before
float temp = 2 * (height + width);
System.out.println(temp);
temp = height * width;
System.out.println(temp);
// after
float perimeter = 2 * (height + width);
System.out.println(perimeter);
float area = height * width;
System.out.println(area);
  • 대입 두번 이상 이뤄진다면 여러 가지 역할을 수행한다는 신호
  • 각자의 역할, 의미를 알 수 있도록 쪼개기
  • 가독성 상승, 유지 보수성 증가

9.2 필드이름 바꾸기#

// before
class Organization {
private final String name;
...
public String name() {return name;}
}
// after
class Organization {
private final String title;
...
public String title() {return title;}
}
  • 더 의미가 명확하게 파악될 수 이름은 아무리 강조해도 지나치지 않다
  • 내용 중 불변 데이터 내용도 다시 한번 강조함

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

// before
public void setDiscount(int number) {
int old = this.discount;
this.discount = number;
this.discountedTotal += old - number;
}
public int discountedTotal() {return this.discountedTotal;}
// after
public void setDiscount(int number) {this.discount = number;}
public int discountedTotal() {
return this.baseTotal - this.discount;
}
  • 가변 데이터가 많은 문제의 원인이 됨
  • 가변 데이터의 유효 범위를 가능한 좁혀야 함
  • 값을 쉽게 계산할 수 있다면 위와 같이 계산과정을 통해 획득하게 함으로 써 얻는 이점
    • 단순한 계산식으로 의도성 쉽게 파악
    • 가독성 결과를 변수에 반영하는 것을 깜빡하는 실수를 방지
  • 변형 연산이라면 그대로 나두어도 됨
    • 변형 계산 예
      • 존재하는 데이터를 기반해 계산 결과를 속성으로 제공
      • 데이터 구조를 받아 다른 데이터 구조로 변환해 반환하는 함수 (정적 팩터리 등)

9.4 참조를 값으로 바꾸기#

// before
public void applyDiscount(int discountAmount) {
this.price.discount(discountAmount);
}
// after
public void applyDiscount(int discountAmount) {
this.price = new Money(
this.price.amount() - discountAmount,
this.price.currency());
}
  • 내부 객체 참조에서 값 객체로 만드는 예시
  • 값 객체는 불변이라 사이드이펙트 걱정 X
  • 해당 리팩터링이 안되는 상황은 9.5 에서 다룸

9.5 값을 참조로 바꾸기#

// before
Customer customer = new Customer(customerData);
// after
Customer custormer = customerRepository.get(customerData.id());
  • 9.4와 같이 값 객체로 구성 했을 때 문제점은 해당 데이터를 갱신 해야할 때 여러곳에 동시에 해당 객체가 존재할 때이다. (모든 부분을 한꺼번에 바꿔줘야함 ㅎㅎ)
  • 위와 같은 상황에선 객체 참조로 대체할 수 있다
  • 예시는 리모트 값을 엔티티화 했을 때 엔티티는 단 하나만 존재해야한다는 의미를 내포 하는 것임

9.6 매직 리터럴 바꾸기#

// before
public float potentialEnergy(float mass, float height) {
return mass * 9.81 * height;
}
// after
private static final float STANDARD_GRAVITY = 9.81;
public float potentialEnergy(float mass, float height) {
return mass * STANDARD_GRAVITY * height;
}
// 번외 before
gender.equals(MALE_GENDER);
// 번외 after
isMale(gender);
  • 매직 리터럴(매직 넘버)는 소스 코드에 등작하는 일반적인 리터럴 값을 말한다
  • 위와 같이 상수화 하면 의도를 잘 알아 볼 수 있음
Last updated on