리펙토링: 비슷한 두 함수를 하나의 함수로

shelly·2021년 6월 16일
0

리펙토링

목록 보기
1/1

의식의 흐름으로 한 코딩의 결과물

setFromDate(value) {
  let { to } = this.calendar
  let from = value

  if (Date.parse(from) > Date.parse(to)) {
    to = new Date(from)
    to.setDate(from.getDate() + 1)
  }

  const duration = Math.floor((to - from)/(24*3600*1000))
  if (duration > 30*6) {
    from = new Date(new Date(to).setDate(to.getDate() - 30*6))
    this.$emit('error', this.errorMessage.duration)
  }

  this.calendar = {
    from,
    to
  }
},
  
setToDate(value) {

    let { from } = this.calendar
    let to = value

    if (Date.parse(from) > Date.parse(to)) {
      from = new Date(to)
      from.setDate(to.getDate() - 1)
    }

    const duration = Math.floor((to - from)/(24*3600*1000))
    if (duration > 30*6) {
      to = new Date(new Date(from).setDate(from.getDate() + 30*6 + 1))
      this.$emit('error', this.errorMessage.duration)
    }

    this.calendar = {
      from,
      to
    }
  • 비슷하지만, 같지는 않은 두 메서드
  • 조금씩 다른 부분이 있는게 문제...

1차 리펙토링

setDate(value, e) {
  const isFrom = e.target.id === 'from'

  let from = isFrom ? value : this.calendar.from
  let to = isFrom ? this.calendar.to : value

  if (Date.parse(from) > Date.parse(to)) {
    if (isFrom) {
      to = new Date(from).setDate(from.getDate() + 1)
    } else {
      from = new Date(to).setDate(to.getDate() - 1)
    }
  }

  const duration = Math.floor((to - from) / (24 * 3600 * 1000))

  if (duration > 30 * 6) {
    if (isFrom) {
      from = new Date(new Date(to).setDate(to.getDate() - 30 * 6))
    } else {
      to = new Date(new Date(from).setDate(from.getDate() + 30 * 6))
    }
    this.$emit('error', this.errorMessage.duration)
  }

  this.calendar = {
    from,
    to
  }
},
  • click event로부터 target id를 가져온다.
  • isFrom 플래그를 사용하여 분기하여 from 혹은 to 둘 중 어느 데이터를 수정할 것인지 결정한다.

2차 리펙토링

setDate(value, e) {
  const isFrom = e.target.id === 'from'
  const MAXIMUM_DURATION = 30 * 6 

  let from = isFrom ? value : this.calendar.from
  let to = isFrom ? this.calendar.to : value

  const isInvalidDuration = Date.parse(from) > Date.parse(to)
  if (isInvalidDuration) {
    const validDate = isFrom ? from.getDate() + 1 : to.getDate() - 1
    if (isFrom) {
      to = new Date(from).setDate(validDate)
    } else {
      from = new Date(to).setDate(validDate)
    }
  }

  const duration = Math.floor((to - from) / (24 * 3600 * 1000))
  if (duration > MAXIMUM_DURATION) {

    const maximumDate = isFrom 
    ? to.getDate() - MAXIMUM_DURATION 
    : from.getDate() + MAXIMUM_DURATION

    if (isFrom) {
      from = new Date(new Date(to).setDate(maximumDate))
    } else {
      to = new Date(new Date(from).setDate(maximumDate))
    }

    this.$emit('error', this.errorMessage.duration)
  }

  this.calendar = { from, to }
},
  • 특정 값의 상수화
  • 계산치를 변수에 부여하여 어떤 의미인지 명확하게 명시

0개의 댓글