Kotlin data class와 그 특징에 따른 메소드 개수

메소드 개수 측정하기

컴파일 후 메소드 개수를 측정하는 https://github.com/KeepSafe/dexcount-gradle-plugin 라이브러리를 사용한다.

공정함을 위해 Kotlin Data class 예제에서 예제를 가져왔다.

data class User(val name: String = “”, val age: Int = 0)

1개의 메소드 (생성자일 것이다), 2개의 필드 그리고 1개의 클래스(명백해보인다)를 기대 할 것이다. 어째든 추측 대신 측정을 해보자.

측정

원본 코드
data class User(val name: String = “”, val age: Int = 0)

Methods = 18

Fields = 2

Classes = 3

Oh gosh!!18 methods, and_3 classes_instead of 1. Why is it so many?

Let’s strip it down a little more

Remove the default argument

data class User(val name: String, val age: Int = 0)

Methods = 16
Fields = 2
Classes = 3

Interesting, we now have 2 methods reduce._Default argument_introduced additional functions indeed.

note: I did the same for `age`, but no different with or without default parameter

Make variable nullable

data class User(val name: String?, val age: Int = 0)

Methods = 5
Fields = 2
Classes = 2

Wow, make thenamenullable, we reduce the method counts by 11. Not only that, we also eliminate a class!

note: I did the same for `age`, but no different both for nullable or non-nullable

Remove the data keyword

class User(val name: String?, val age: Int = 0)

Methods = 1
Fields = 2
Classes = 1

Finally… now this matches my initial way of counting. Back to the most basic.

Conclusion

In short, there are some cost in term of methods and classes count when we use non-nullable, default parameter and data classes. Please don’t get me wrong. I’m not advocating that we should not use them. I like them as they make the codes more concise and also safer.

However, if they are not needed, don’t just make them one. E.g. don’t convert all model classes to data classes, but only if you need to take advantage of the data class features.

Don’t use it if you don’t need it. There’s always a cost.

results matching ""

    No results matching ""