-
[EffectiveKotlin] 변수의 스코프를 최소화하라언어/Kotlin 2022. 3. 7. 21:50반응형
kotlin은 스코프를 최소화 하는데 있어서 좀 더 진보한 방식을 사용한다.
1. if 문
// 나쁜 예 val user: User if (hasValue) { user = getValue() } else { user = User() } // 좋은 예 val user = if (hasValue) { getValue() } else { User() }
2. if-else 문
// 나쁜 예 fun updateWeather(degrees: Int) { val description: String val color: Int if (degrees < 5) { description = "cold" color = Color.BLUE } else if (degrees < 23) { description = "mild" color = Color.YELLOW } else { description = "hot" color = Color.RED } } // 좋은 예 fun updateWeather(degrees: Int) { val (description, color) = when { degrees < 5 -> "cold" to Color.BLUE degrees < 23 -> "mild" to Color.YELLOW else -> "hot" to Color.RED } }
3. Collections
// 나쁜 예 val numbers = mutableListOf(1, 2, 3) numbers.add(4) numbers.add(5) // 좋은 예 val numbers = mutableListOf(1, 2, 3).apply { this.add(4) this.add(5) }.toList()
apply를 사용해 list를 초기화하면, 불변 객체로 가변성을 제한 할 수 있는 장점 또한 추가된다.
4. 캡처링 (coroutine)
에라토스테네스의 체(소수를 구하는 알고리즘)
val primes = sequence { // it은 이전 원소 val numbers = generateSequence(2) { it + 1 } while (true) { val prime = numbers.first() yield(prime) numbers = numbers.drop(1) .filter { it % prime != 0 } } } print(primes.take(10).toList()) // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
위 문제를 좀 더 최적화하기 위해 아래와 같이 변경하는 경우가 있다.
var prime: Int while (true) { prime = numbers.first() . . } print(prime.take(10).toList()) // [2, 3, 5, 6, 7, 8, 9, 10, 11, 12]
그런데, 이렇게 하면 실행결과가 제대로 나오지 않는다.
5. 결론
※ 좁은 스코프에 걸쳐 있을 수록, 그 변경을 추적하는 것이 쉽다.
반응형'언어 > Kotlin' 카테고리의 다른 글
[EffectiveKotlin] 예외를 활용해 코드에 제한을 걸어라 (0) 2022.03.17 [EffectiveKotlin] 가독성을 목표로 설계하라 (0) 2022.03.16 [EffectiveKotlin] 타입을 명확하게 지정하라 (0) 2022.03.13 [EffectiveKotlin] 최대한 플랫폼 타입을 사용하지 말라 (0) 2022.03.10 [EffectiveKotlin] 가변성을 제한하라 (0) 2022.02.28