หลังดูบอลมานั่งเขียน Android app ด้วยภาษา Kotlin กันหน่อย
ซึ่งเป็นภาษาที่มีความสามารถที่ดีมากมาย
หนึ่งในนั้นคือ Data Class ที่ Java Developer ถือว่าเป็น killer feature เลยนะ
เพราะว่า ไม่ต้องมาเขียนหรือ generate getter/setter method เอง
ดังนั้นทุกคนก็จะ convert พวก POJO class มาเป็น Data Class กันหมดเลย
รู้กันไหมว่า ความสามารถนี้มันมาพร้อม cost นะ
มาลองดูกัน

นักพัฒนา Android app ทุกคนรู้ว่า

ทุกสิ่งอย่างที่นำมาใช้ในการพัฒนา Android app นั้น ล้วนมีค่าใช้จ่ายทั้งนั้น
เนื่องจากมันส่งผลต่อ จำนวน method ของ app
ซึ่ง Android app มีจำกัดให้ 64K method
ถ้ามีจำนวนเกินนี้ก็ต้องเข้าสู่โลกของ Multi-Dex
นั่นหมายความว่า ต้องใช้เวลาในการ build มากขึ้น
ดังนั้น เราจึงควรต้องจัดการให้ดี

โดยปกติการนับจำนวน method นั้น
มักจะใช้งาน plugin ชื่อว่า Dexcount gradle plugin

มาดูกันสิว่า Data Class มันเป็นอย่างไรบ้าง ?

เริ่มด้วยการสร้าง Android project ด้วยภาษา Kotlin ใน Android Studio
นับจำนวน method ได้ดังนี้

Total methods in app-debug.apk: 23512 (35.88% used)
Total fields in app-debug.apk:  11117 (16.96% used)
Total classes in app-debug.apk:  2648 (4.04% used)
Methods remaining in app-debug.apk: 42023
Fields remaining in app-debug.apk:  54418
Classes remaining in app-debug.apk:  62887

จากนั้นสร้าง Data class แบบง่าย ๆ ดังนี้

data class User(val id: Int = 0, val firstname: String = "")

ลองนับจำนวน method ได้ดังนี้

Total methods in app-debug.apk: 23524 (35.90% used)
Total fields in app-debug.apk:  11119 (16.97% used)
Total classes in app-debug.apk:  2649 (4.04% used)
Methods remaining in app-debug.apk: 42011
Fields remaining in app-debug.apk:  54416
Classes remaining in app-debug.apk:  62886

สิ่งที่เพิ่มขึ้นมาคือ
1 class
2 field
12 method

มาจากไหนตั้ง 12 method นะ ?
เยอะใช้ได้เลยนะ

  1. equals()
  2. hashCode()
  3. toString()
  4. copy()
  5. componentN()
  6. กำหนดค่า default argument
  7. primary constructor

ลองไม่ใช้ default argument หน่อยสิ

data class User(val id: Int, val firstname: String)

ผลที่ได้เป็นดังนี้

Total methods in app-debug.apk: 23522 (35.89% used)
Total fields in app-debug.apk:  11119 (16.97% used)
Total classes in app-debug.apk:  2649 (4.04% used)
Methods remaining in app-debug.apk: 42013
Fields remaining in app-debug.apk:  54416
Classes remaining in app-debug.apk:  62886

จะเห็นว่า จำนวน method ลดลงไป 2 method
แสดงว่าแค่ default argument ของแต่ละ field ก็คือ 1 method นะ

ลองเอา keyword data ออกไปหน่อยสิ ?

class User(val id: Int, val firstname: String)

จำนวน method ลดลงไปอีก 7 method !!!
นั่นคือเพิ่มจากเริ่มต้นเพียง 3 method เท่านั้น
ดังนี้

Total methods in app-debug.apk: 23515 (35.88% used)
Total fields in app-debug.apk:  11119 (16.97% used)
Total classes in app-debug.apk:  2649 (4.04% used)
Methods remaining in app-debug.apk: 42020
Fields remaining in app-debug.apk:  54416
Classes remaining in app-debug.apk:  62886

สุดท้ายแล้ว

ก่อนจะใช้งานต้องรู้และเข้าใจก่อน
ใช้เท่าที่จำเป็นเท่านั้น
เพราะว่าทุกสิ่งอย่างมันมีค่าใช้จ่ายตามมาเสมอ

โดยที่ Kotlin library ก็มีจำนวน method ตามนี้