ReactMasters / study

스터디 기록
1 stars 0 forks source link

11월 3주차 리팩토링(매개변수 객체 만들기, 변수 인라인하기, 함수 선언 바꾸기, 매개변수를 질의함수로 바꾸기) #32

Open JeGwan opened 2 years ago

JeGwan commented 2 years ago

Introduce parameter object

배경

예시

function amountInvoice(startDate: Date, endDate: Date) {
  // ...
}

function amountOverdue(startDate: Date, endDate: Date) {
  // ...
}

// into

function amountInvoice(dateRage: [Date, Date]) {
  // ...
}

function amountOverdue(dateRage: [Date, Date]) {
  // ...
}

장점

절차

  1. 적당한 데이터 구조가 마련되어있지 않으면 새로 만든다.
  2. 테스트한다.
  3. 함수선언 바꾸기로 새데이터 구조를 매개변수로 추가한다.
  4. 테스트한다.
  5. 함수 호출 시 새로운 데이터 구조 인스턴스를 넘기도록 수정한다. 수정할 때 마다 테스트한다.
  6. 기본 매개변수를 사용하던 코드를 새 데이터 구조의 원소를 사용하도록 바꾼다.
  7. 다 바꿨다면 기존 매개변수를 제거하고 테스트한다.

예시

const station = {
  name: 'ZB1',
  readings: [
    { temp: 47, time: '2020-11-10 09:10' },
    { temp: 54, time: '2020-11-11 09:10' },
    { temp: 32, time: '2020-11-12 09:10' },
    { temp: 39, time: '2020-11-13 09:10' },
    { temp: 22, time: '2020-11-14 09:10' },
  ],
}

function readingsOutsideRange(station, min, max) {
  return station.readings.filter(r => r.temp < min || r.temp > max)
}

const alerts = readingsOutsideRange(station, operatingPlan.temperatureFloor, operationgPlan.temperatureCeiling)

// 1. min, max를 묶어 표현하는 클래스를 만들어보자.

class NumberRange {
  constructor(min, max) {
    this._data = { min, max }
  }
  get min() {
    return this._data.min
  }
  get max() {
    return this._data.max
  }
}

// 2. NumberRange 타입의 데이터를 넣을 수 있게 함수에 매개변수를 추가한다.

function readingsOutsideRange(station, min, max, range) {
  return station.readings.filter(r => r.temp < min || r.temp > max)
}

// 3. 호출문엔 일단 null을 넣는다.

const alerts = readingsOutsideRange(station, operatingPlan.temperatureFloor, operationgPlan.temperatureCeiling, null)

// 4. 호출문을 바꾼다.

const range = new NumberRange(operatingPlan.temperatureFloor, operationgPlan.temperatureCeiling)
const alerts = readingsOutsideRange(station, operatingPlan.temperatureFloor, operationgPlan.temperatureCeiling, range)

// 5. 기존 매개변수 사용부분을 변경한다.
function readingsOutsideRange(station, range) {
  return station.readings.filter(r => r.temp < range.min || r.temp > range.max)
}

// 6. 호출부의 안쓰는 매개변수도 없앤다.
const range = new NumberRange(operatingPlan.temperatureFloor, operationgPlan.temperatureCeiling)
const alerts = readingsOutsideRange(station, range)

Inline variable

배경

예시

function isBigBasePrice(order) {
  const basePrice = order.basePrice
  return basePrice > 1000
}

// into

function isBigBasePrice(order) {
  return order.basePrice > 1000
}

Change function declaration

배경

예시

function circum() {}

// into

function circumference() {}

Replace Parameter with Query

배경

예시

availableVacation(employee, empleyee.grade)
function availableVacation(employee, grade) {
  // ...
}

// into

availableVacation(employee)
function availableVacation(employee) {
  const grade = employee.grade
}