2/24 수업

hyunji·2023년 2월 24일
0

Lotto - 점진적인 리팩토링

val lotto  = listOf(1,2,3,4,5,6).map(::LottoNumber)
  • 테스트 코드 시 한번에 로또 넘버로 감싸는 법
private fun List<LottoNumber>.match2(winningLotto: List<LottoNumber>): Int{
	return return count{ winningLotto.contains(it) }
}

//
val matchCount = userLotto.match2(winningLotto)

//
//이걸 Lotto 클래스로 옮김
fun match(winningLotto: Lotto) :Int{
	return this.number.contains(it)
}
  • 로또 안에서 이 로직을 행하도록 수정
  • 이름도 점진적으로 리팩토링 하기
    * winningLotto -> Lotto
    match 함수 안에서는 이 로또가 위닝로또인지 중요하지 않기 때문
  • winningLotto + BonusNumber = WinningLotto 묶기
  • WinningLotto 클래스 안에도 match 함수 추가
    ->winningLotto.match(userLotto)
  • 테스트 시
fun Lotto(vararg number: Int): Lotto{
	return Lotto(numbers.map(::LottoNumber))
}

이렇게 가변인자를 사용해 로또를 만들어주는 함수를 만들면 좀더 간편하게 적기 가능

  • 이걸 더 간편하게 생성자로 추가하면 아래처럼 적으면 됨 - GOOD
constructor(vararg numbers: Int): this(numbers.map(::LottoNumber))

리팩토링 시 commit

  • 점진적인 리팩토링 시 테스트가 깨지지 않게 리팩토링 해야함
  • 따라서 commit도 리팩토링 중간중간 계속 해주면 된다.

some Tips...

@Disabled = 테스트 무시하는 코드

  • 나중에는 commit message를 정해놓고 그거에 대해서만 개발해보기도 도전해보기
  • 클래스 간의 양방향의존 VS 단방향의존 생각해보기

방어적 복사

class LottoNumbers(numbers: List<Int>){
  	private val _numbers: MutableList<Int> = numbers.toMutableList()
	val numbers: List<Int> 
    	get() = _numbers.toList) //커스텀게터
    
    fun add(number: Int){
    	_numbers = add(number)
    }
    
    fun clear(){
    	_numbers = clesr()
    }
}
  • 새로운 리스트 변수를 선언하고 거기에 넣는다

  • toList()도 해주기

  • 값이 변경되는 것은
    val VS var 의 문제 X / List VS MutableList 의 문제

  • 백킹프로퍼티 = 뒷받침해주는 프로퍼티(_numbers)

  • 여기서 어떻게 numbers를 뚫 것인가????
    actual.numbers as MutableList<Int>.add(7)

    • JAVA 때문에 이게 된다
    • 자바는 둘다 List다.
    • 따라서 형 변환해주면 뚫리는 거다~!

0개의 댓글