ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
ဒါက နောက်ဆုံး lesson ပါ။ Task Manager က ထည့်တာ၊ ပြီးအောင်လုပ်တာ၊ ရှာတာ လုပ်နိုင်ပြီးသားပါ။ အခု သူ့ကိုယ်သူ report လုပ်တာနဲ့ program ရပ်သွားပြီးနောက်မှာ task တွေကို မှတ်ထားတာကို သင်ပေးပါမယ်။ Report က ဘယ်လောက်ပြီးပြီလဲ၊ နောက်ဘာလုပ်ရမလဲ လို မေးခွန်းတွေကို ဖြေပြီး သိမ်းထားတဲ့ file က မနက်ဖြန် run ကို ဒီနေ့ ရပ်ခဲ့တဲ့နေရာကနေ ဆက်သွားခွင့် ပေးပါတယ်။
ဆိုင်ပိတ်ချိန်မှာ ဆိုင်ပိုင်ရှင်တစ်ယောက်ကို စဉ်းစားကြည့်ပါ။ သူက ဒီနေ့ရောင်းအားကို ရေတွက်တယ်၊ ဆိုင်ဖက်အတွက် အကျဉ်းချုပ်လေး ရေးတယ်၊ ပြေစာတွေကို အံဆွဲထဲ သိမ်းတယ်။ နောက်မနက် အံဆွဲဖွင့်ပြီး ဆက်လုပ်ပါတယ်၊ ပြေစာတစ်စောင် မှုန်ပြီး ဖတ်မရရင်တောင် ဆိုင်ကို မပိတ်ဘဲ အဲဒီတစ်စောင်ကို ဘေးချထားလိုက်ပါတယ်။ အကျဉ်းချုပ်က Reportable interface၊ အံဆွဲက file၊ မှုန်နေတဲ့ ပြေစာကို ဘေးချတာက defensive reader ပါ။
Problem → Why → Solution
ပြဿနာ: file ကို အယုံကြည်လွန်တဲ့ loader
Persistence ကတော့ ပထမ draft တွေ အနာဆုံးနေရာပါ။ အောက်က draft က လူတွေ ပထမဆုံး ရေးတတ်တဲ့ loader ပုံစံပါ။ pipe နဲ့ split လုပ်တယ်၊ toInt() နဲ့ valueOf() ကို ခေါ်တယ်၊ list တစ်ခုလုံးကို map လုပ်ပါတယ်။ Program ကိုယ်တိုင် ရေးထားတဲ့ file မှာတော့ အလုပ်လုပ်လို့ demo က အောင်ပါတယ်။
တကယ့် file တွေက ပိုရှုပ်ပါတယ်။ Task မဟုတ်တဲ့ line၊ လက်နဲ့ URGENT လို့ ပြင်ထားတဲ့ priority၊ ခွဲတဲ့ character ကိုယ်တိုင်ပါနေတဲ့ title တို့ကြောင့် loader က exception ပစ်ပြီး line တစ်ကြောင်းမကောင်းတာနဲ့ ကျန် task အားလုံး ပျောက်ပါတယ်။ Report code ကလည်း စိတ်ထားအတူတူပါပဲ။ Int ကို သုညနဲ့ စားရင် ArithmeticException ပစ်လို့ empty list ပေါ်မှာ percentage တွက်ရင် program ပြီးသွားပါတယ်။
enum class Priority { LOW, MEDIUM, HIGH }
data class Task(val id: Int, val title: String, val priority: Priority)
// File format: id|title|priority
fun loadDraft(lines: List<String>): List<Task> =
lines.map { line ->
val parts = line.split("|")
Task(parts[0].toInt(), parts[1], Priority.valueOf(parts[2]))
}
fun main() {
val samples = listOf(
"1|Pay rent|HIGH", // fine
"oops", // not a task at all
"7|Fix|URGENT", // priority edited by hand
"3|a|b|HIGH", // the title contains the separator
)
for (line in samples) {
try {
println(loadDraft(listOf(line)))
} catch (e: Exception) {
println("${e::class.simpleName}: ${e.message}")
}
}
}Line တစ်ကြောင်း မကောင်းတာနဲ့ ဘာကြောင့် အားလုံးပျက်တာလဲ
map က line တိုင်းမှာ parsing ကို လုပ်ပြီး exception တစ်ခုခု ထွက်ရင် အလယ်ကနေ လွတ်ထွက်သွားလို့ caller က ဘာမှ မရတော့ပါဘူး။ toInt() နဲ့ valueOf() နှစ်ခုလုံးက မမှန်တဲ့ input ကို throw နဲ့ ပြောပြီး programming အမှားအတွက်တော့ မှန်ပေမယ့် program အပြင်က ဖတ်တဲ့ data အတွက်တော့ မမှန်ပါဘူး။ Disk ဒါမှမဟုတ် network က data ကို မယုံကြည်ရဘူးလို့ သဘောထားရပါမယ်။ Line တစ်ကြောင်းချင်းစီကို Task? အဖြစ် parse လုပ်ပြီး မအောင်မြင်တာတွေကို ဘာလုပ်မလဲ ဆုံးဖြတ်ပါ။
Core concept: စာချုပ်၊ သေချာတဲ့ ဂဏန်းတွက်ချက်မှုနဲ့ ကာကွယ်တဲ့ reader
Part 3 က Task Manager ကို နောက်ဆုံး အလွှာ ထည့်ပါတယ်။ အောက်က အယူအဆလေးခုစီက program ကို တကယ်သုံးမှသာ ပေါ်လာတဲ့ ပြဿနာတွေကို ဖြေရှင်းပါတယ်။ Report တစ်မျိုးထက်ပိုတာ၊ ဂဏန်းတွေမှာ tie နဲ့ empty data ပါတာ၊ တခြားသူ ပြင်နိုင်တဲ့ file ရှိတာတွေပါ။
၁။ Interface ဆိုတာ ကတိတစ်ခုပါ
interface Reportable က summary() ကို ကြေညာပြီး printSummary() ကို အဲဒါပေါ်မှာ တည်ဆောက်ထားတဲ့ default body ပေးပါတယ်။ : Reportable လို့ ပြောတဲ့ class က summary() ကို ပေးရမယ်၊ override လို့ မှတ်ရမယ်၊ keyword မေ့ရင် compile error ပါ။ Reportable ကိုင်ထားတဲ့ ဘယ်သူမဆို TaskManager လား တခြားအရာလား မသိဘဲ summary တောင်းလို့ရပါတယ်၊ ဒါကြောင့် challenge မှာ implementation ဒုတိယတစ်ခု ထပ်ထည့်ခိုင်းတာပါ။
၂။ Report ဆိုတာ group၊ count၊ sort
groupBy { it.priority } က တကယ်ရှိတဲ့ key တွေပဲ ပါတဲ့ Map<Priority, List<Task>> ကို ပြန်ပေးလို့ report က Priority.entries ကို loop ပတ်ပြီး orEmpty() နဲ့ task သုညခုရှိတဲ့ level တွေကိုပါ ပြပါတယ်။ ဖွင့်ထားတဲ့ task စာရင်းအတွက် sortedWith(compareByDescending<Task> { it.priority }.thenBy { it.id }) က sort က တူတဲ့ element တွေကို ဘယ်လိုကိုင်မလဲ မှန်းရတာထက် tie-break ကို ဖော်ပြတိုက်ရိုက် ပြောထားပါတယ်။
၃။ Percentage: Double နဲ့ မြှောက်၊ နောက်ဆုံးမှ စား၊ သုညကို စောင့်ကြည့်
done * 100.0 / total က စားတာကို Double မှာ ထိန်းထားပြီး roundToInt() က 33.3 ကို 33 ဖြစ်စေပါတယ်။ done / total * 100 က Int နှစ်ခုကို အရင်စားလို့ task အားလုံး မပြီးမချင်း 0 ပေးပါတယ်။ Empty list ကတော့ သူ့ကိုယ်ပိုင် early return လိုပါတယ်၊ သုညနဲ့ စားရင် Int အတွက် ArithmeticException၊ Double အတွက် NaN ဖြစ်ပြီး NaN ကို round မလုပ်နိုင်လို့ပါ။
၄။ File: task တစ်ခုကို line တစ်ကြောင်း ရေး၊ ကာကွယ်ပြီး ဖတ်
TaskStore က id|priority|isDone|title ကို free-text title ကို နောက်ဆုံးမှာထားပြီး ရေးကာ split("|", limit = 4) နဲ့ ပြန်ဖတ်လို့ pipe ပါတဲ့ title လည်း အမှန်အတိုင်း ပြန်ရပါတယ်။ decode() က Task? ပြန်ပေးပြီး မအောင်မြင်တဲ့ လမ်းကြောင်းတိုင်းက null ပြန်ပါတယ်၊ mapNotNull က ကောင်းတဲ့ line တွေကို ထိန်းထားပြီး load() က ကျန်တာတွေကို skipped အဖြစ် ရေတွက်ပါတယ်။ ပြီးရင် replaceAll() က nextId ကို load လုပ်ထားတဲ့ အကြီးဆုံး id ရဲ့ နောက်ကနေ ပြန်စလို့ task အသစ်တွေက အဟောင်းတွေနဲ့ မတိုက်ပါဘူး။
| Edge case | Code က ဘယ်လိုကိုင်တွယ်လဲ | ရလဒ် |
|---|---|---|
| Task လုံးဝ မရှိ | summary() က စောစောပြန်တယ် | No tasks yet |
| Title ထဲမှာ | ပါတယ် | Title က နောက်ဆုံး၊ split(limit = 4) | Title အပြည့်အစုံ ပြန်ရတယ် |
| ပျက်နေ ဒါမှမဟုတ် လက်နဲ့ပြင်ထားတဲ့ line | decode() က null ပြန်တယ် | ကျော်ပြီး ရေတွက်တယ် |
| Load ပြီး ပြန်စတယ် | nextId = အကြီးဆုံး id + 1 | Id မထပ်ဘူး |
- ကတိကို ရေး (Reportable)
- Data ကို group၊ count၊ sort လုပ်
- Task တစ်ခုကို line တစ်ကြောင်း သိမ်း
- ကာကွယ်ပြီး ဖတ်: ကျော်၊ crash မဖြစ်စေနဲ့
ကိုယ်ပိုင် output ကို ယုံလို့ရတယ်၊ အပြင်ကနေ ပြန်ဖတ်တာကိုတော့ မယုံရဘူး။
အခြေခံ ပုံစံ
interface Reportable {
fun summary(): String
fun printSummary() = println(summary())
}
class Manager : Reportable {
override fun summary(): String = "..."
}
val groups = items.groupBy { it.kind }
val ordered = items.sortedWith(compareByDescending<Item> { it.rank }.thenBy { it.id })
val parts = line.split("|", limit = 3)Interface က class က ဘာလုပ်မယ်လို့ ကတိပေးတာကို ပြောပြီး groupBy နဲ့ sortedWith က report အတွက် data ကို ပုံဖော်ပေးကာ limit ပါတဲ့ split က ခွဲတဲ့ character ပါနိုင်တဲ့ နောက်ဆုံး field ကို မပျက်စေဘဲ ထိန်းပေးပါတယ်။
Part 3 code: ပြီးစီးတဲ့ Task Manager
ဒါက program အပြည့်အစုံပါ၊ highlight လုပ်ထားတဲ့ စာကြောင်းတွေက Part 3 မှာ အသစ်တွေပါ။ import တွေ၊ repository ထဲက replaceAll()၊ Reportable interface၊ report command နဲ့ summary()၊ TaskStore နဲ့ scripted main ပါ။ main က task တွေကို temporary directory ထဲက file မှာ ရေးပြီး လက်နဲ့ပြင်ထားတဲ့ file ကို အတုလုပ်ဖို့ ပျက်နေတဲ့ line နှစ်ကြောင်း ထပ်ထည့်ကာ ပြန် load လုပ်ပြီး finally မှာ ရှင်းလင်းလို့ ဘာမှ ကျန်မနေဘဲ path ကိုလည်း ဘယ်တော့မှ print မထုတ်ပါဘူး။
import java.nio.file.Files
import java.nio.file.Path
import kotlin.math.roundToInt
enum class Priority { LOW, MEDIUM, HIGH }
data class Task(
val id: Int,
val title: String,
val priority: Priority,
val isDone: Boolean = false,
)
class TaskRepository {
private val tasks = mutableListOf<Task>()
private var nextId = 1
fun add(title: String, priority: Priority = Priority.MEDIUM): Task {
require(title.isNotBlank()) { "Task title must not be blank" }
val task = Task(id = nextId++, title = title.trim(), priority = priority)
tasks.add(task)
return task
}
fun findById(id: Int): Task? = tasks.firstOrNull { it.id == id }
fun complete(id: Int): Task? {
val index = tasks.indexOfFirst { it.id == id }
if (index == -1) return null
val completed = tasks[index].copy(isDone = true)
tasks[index] = completed
return completed
}
fun search(predicate: (Task) -> Boolean): List<Task> = tasks.filter(predicate)
fun all(): List<Task> = tasks.toList()
fun replaceAll(restored: List<Task>) {
tasks.clear()
tasks.addAll(restored)
nextId = (restored.maxOfOrNull { it.id } ?: 0) + 1
}
}
interface Reportable {
fun summary(): String
fun printSummary() = println(summary())
}
class TaskManager(private val repo: TaskRepository) : Reportable {
fun execute(line: String): String {
val parts = line.trim().split(" ", limit = 3)
return when (parts[0].lowercase()) {
"add" -> add(parts.getOrNull(1), parts.getOrNull(2))
"done" -> done(parts.getOrNull(1))
"list" -> list(parts.getOrNull(1))
"find" -> find(parts.drop(1).joinToString(" "))
"report" -> summary()
"" -> "Type a command: add, done, list, find or report"
else -> "Unknown command '${parts[0]}'"
}
}
override fun summary(): String {
val tasks = repo.all()
if (tasks.isEmpty()) return "No tasks yet"
val byPriority = tasks.groupBy { it.priority }
val lines = mutableListOf("=== Task summary ===")
for (priority in Priority.entries.reversed()) {
val group = byPriority[priority].orEmpty()
val finished = group.count { it.isDone }
lines += "${priority.name.padEnd(6)} $finished/${group.size} done"
}
val doneCount = tasks.count { it.isDone }
lines += "Completed: ${(doneCount * 100.0 / tasks.size).roundToInt()}%"
lines += "--- Still open, most urgent first ---"
val open = tasks.filter { !it.isDone }
.sortedWith(compareByDescending<Task> { it.priority }.thenBy { it.id })
lines += if (open.isEmpty()) listOf("(nothing left)") else open.map { format(it) }
return lines.joinToString("\n")
}
private fun add(priorityText: String?, title: String?): String {
if (priorityText == null || title.isNullOrBlank()) {
return "Usage: add <low|medium|high> <title>"
}
val priority = parsePriority(priorityText)
?: return "Unknown priority '$priorityText'"
return "Added " + format(repo.add(title, priority))
}
private fun done(idText: String?): String {
val id = idText?.toIntOrNull() ?: return "Usage: done <id>"
return repo.complete(id)
?.let { "Completed " + format(it) }
?: "No task with id $id"
}
private fun list(priorityText: String?): String {
if (priorityText == null) return render(repo.all())
val priority = parsePriority(priorityText)
?: return "Unknown priority '$priorityText'"
return render(repo.search { it.priority == priority })
}
private fun find(text: String): String {
if (text.isBlank()) return "Usage: find <text>"
return render(repo.search { it.title.contains(text, ignoreCase = true) })
}
private fun parsePriority(text: String?): Priority? =
Priority.entries.firstOrNull { it.name.equals(text, ignoreCase = true) }
private fun format(task: Task): String {
val mark = if (task.isDone) "[x]" else "[ ]"
return "$mark #${task.id} ${task.title} (${task.priority})"
}
private fun render(tasks: List<Task>): String =
if (tasks.isEmpty()) "(no matching tasks)"
else tasks.joinToString("\n") { format(it) }
}
data class LoadResult(val tasks: List<Task>, val skipped: Int)
class TaskStore(private val file: Path) {
fun save(tasks: List<Task>) {
val lines = tasks.map { "${it.id}|${it.priority}|${it.isDone}|${it.title}" }
Files.write(file, lines)
}
fun load(): LoadResult {
if (!Files.exists(file)) return LoadResult(emptyList(), 0)
val lines = Files.readAllLines(file).filter { it.isNotBlank() }
val tasks = lines.mapNotNull { decode(it) }
return LoadResult(tasks, lines.size - tasks.size)
}
private fun decode(line: String): Task? {
val parts = line.split("|", limit = 4)
if (parts.size != 4) return null
val id = parts[0].toIntOrNull() ?: return null
val priority = Priority.entries.firstOrNull { it.name == parts[1] } ?: return null
val isDone = parts[2].toBooleanStrictOrNull() ?: return null
return Task(id, parts[3], priority, isDone)
}
}
fun main() {
val dir = Files.createTempDirectory("taskmanager-")
val file = dir.resolve("tasks.txt")
try {
val repo = TaskRepository()
val manager = TaskManager(repo)
manager.printSummary()
listOf(
"add high Review Kotlin syntax",
"add medium Practice data classes",
"add high Practice lambdas | pipes are fine",
"add low Learn interfaces",
"add high Finish the project",
"done 1",
"done 3",
).forEach { println("> $it"); println(manager.execute(it)) }
manager.printSummary()
val store = TaskStore(file)
store.save(repo.all())
println("Saved ${Files.readAllLines(file).size} tasks")
val damage = "oops|not a task\n9|URGENT|false|Bad\n"
Files.writeString(file, Files.readString(file) + damage)
val loaded = store.load()
println("Loaded ${loaded.tasks.size}, skipped ${loaded.skipped} damaged lines")
val restored = TaskRepository().apply { replaceAll(loaded.tasks) }
println(TaskManager(restored).execute("add low Write the next lesson"))
} finally {
Files.deleteIfExists(file)
Files.deleteIfExists(dir)
}
}Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Interface with a default method
fun printSummary() = println(summary())printSummary() မှာ body ပါလို့ implement လုပ်သူတွေက အလကား ရပြီး summary() ကိုပဲ ရေးရပါတယ်။ TaskManager က summary() ကို override လုပ်ပြီး main က printSummary() ကို နှစ်ခါခေါ်ပါတယ်။ တစ်ခါက empty manager မှာ၊ တစ်ခါက task တွေ ရှိပြီးနောက်မှာပါ။
- Show empty levels too
val group = byPriority[priority].orEmpty()groupBy က ရှိတဲ့ key တွေကိုပဲ ဆောက်ပါတယ်။ မရှိတဲ့ key ကို ရှာရင် null ရပြီး orEmpty() က အဲဒါကို empty list ဖြစ်စေလို့ task မရှိတဲ့ level က crash မဖြစ်ဘဲ 0/0 done လို့ ပြပါလိမ့်မယ်။
- Stable ordering
.sortedWith(compareByDescending<Task> { it.priority }.thenBy { it.id })Priority အမြင့်ဆုံးက အရင်၊ priority တူတဲ့ task တွေက ဖန်တီးတဲ့ အစီအစဉ်အတိုင်း ဖြစ်ပါတယ်။ ဒါကြောင့် report မှာ #5 (HIGH) က #2 (MEDIUM) ရှေ့၊ #2 က #4 (LOW) ရှေ့မှာ ပေါ်ပါတယ်။
- Percentage on Doubles
lines += "Completed: ${(doneCount * 100.0 / tasks.size).roundToInt()}%"၅ ခုမှာ ၂ ခုပြီးတာက Double division ပြီးရင် 40.0 ဖြစ်ပြီး roundToInt() က 40 လုပ်ပေးပါတယ်။ Empty list ကိစ္စက ဒီစာကြောင်းကို မရောက်ပါဘူး၊ summary() က စောစောပြန်ပြီးသားမို့ပါ။
- Free-text field goes last
val parts = line.split("|", limit = 4)အများဆုံး အပိုင်းလေးခုပဲ ထွက်လို့ တတိယ pipe နောက်က အားလုံး title ထဲမှာပဲ ကျန်ပါတယ်။ Task 3 ရဲ့ title မှာ pipe ပါပေမယ့် round trip ကို ကျော်ဖြတ်ပြီး မပျက်ပါဘူး။
- Null means skip
val id = parts[0].toIntOrNull() ?: return nulldecode() ရဲ့ မအောင်မြင်တဲ့ လမ်းကြောင်းတိုင်းက throw မလုပ်ဘဲ null ပြန်ပါတယ်။ load() က mapNotNull နဲ့ ကောင်းတဲ့ line တွေကို ထိန်းပြီး ကျန်တာတွေကို skipped အဖြစ် ရေတွက်ပါတယ်၊ ဒီမှာတော့ oops|not a task နဲ့ URGENT line ပါ။
- Cleanup in finally
Files.deleteIfExists(file)အပေါ်မှာ တစ်ခုခု throw လုပ်ရင်တောင် temporary file နဲ့ directory ကို ဖျက်ပါတယ်။ Directory ကို နောက်ဆုံးမှ ဖျက်တာက အရင် ဗလာဖြစ်နေရလို့ပါ။
No tasks yet
> add high Review Kotlin syntax
Added [ ] #1 Review Kotlin syntax (HIGH)
> add medium Practice data classes
Added [ ] #2 Practice data classes (MEDIUM)
> add high Practice lambdas | pipes are fine
Added [ ] #3 Practice lambdas | pipes are fine (HIGH)
> add low Learn interfaces
Added [ ] #4 Learn interfaces (LOW)
> add high Finish the project
Added [ ] #5 Finish the project (HIGH)
> done 1
Completed [x] #1 Review Kotlin syntax (HIGH)
> done 3
Completed [x] #3 Practice lambdas | pipes are fine (HIGH)
=== Task summary ===
HIGH 2/3 done
MEDIUM 0/1 done
LOW 0/1 done
Completed: 40%
--- Still open, most urgent first ---
[ ] #5 Finish the project (HIGH)
[ ] #2 Practice data classes (MEDIUM)
[ ] #4 Learn interfaces (LOW)
Saved 5 tasks
Loaded 5, skipped 2 damaged lines
Added [ ] #6 Write the next lesson (LOW)Integer division နဲ့ rounding
Percentage စာကြောင်းက အလွန်ဖြစ်လေ့ရှိတဲ့ bug မိသားစုရဲ့ ဥပမာသေးသေးလေးပါ။ အောက်က snippet က လုပ်ဆောင်ချက် အစီအစဉ်မှားနှစ်မျိုး၊ ဘေးကင်းတဲ့ helper နဲ့ ပိုင်းခြေသုညက Int division ကို ဘာလုပ်လဲ ဆိုတာ ပြပါတယ်။
import kotlin.math.roundToInt
fun percentDone(done: Int, total: Int): Int =
if (total == 0) 0 else (done * 100.0 / total).roundToInt()
fun main() {
println(2 / 3 * 100)
println(2 * 100 / 3)
println(percentDone(2, 3))
println(percentDone(1, 3))
println(percentDone(0, 0))
val zero = 0
try {
println(5 / zero)
} catch (e: ArithmeticException) {
println("${e::class.simpleName}: ${e.message}")
}
}2 / 3 * 100 က 0 ထွက်တာက 2 / 3 ဆိုတာ မြှောက်ခြင်း မလုပ်ခင်မှာ 0 ပေးတဲ့ Int division မို့ပါ၊ 2 * 100 / 3 က 66 ထွက်တာက အပိုင်းကိန်းကို round မလုပ်ဘဲ ဖြတ်ပစ်လို့ပါ။ percentDone(2, 3) က 67 အထိ round လုပ်ပြီး percentDone(0, 0) က empty case ကို guard လုပ်ထားလို့ 0 ဖြေပါတယ်။ နောက်ဆုံးစာကြောင်းက Int ကို သုညနဲ့ စားရင် ပစ်တဲ့ exception ကို ပြပါတယ်။
Framework မသုံးဘဲ file format ကို test လုပ်ခြင်း
Test စလုပ်ဖို့ test library မလိုပါဘူး။ check(condition) { message } က condition false ဖြစ်ရင် IllegalStateException ပစ်လို့ ရိုးရိုး main တစ်ခုနဲ့တင် အပြုအမူကို assert လုပ်လို့ရပါတယ်။ Snippet က title သုံးခုကို round trip လုပ်ပါတယ် (တစ်ခုမှာ pipe တွေပါပြီး တစ်ခုမှာ မြန်မာစာပါပါတယ်)၊ ပြီးရင် မကောင်းတဲ့ line ခြောက်မျိုးကို ငြင်းတာကို အတည်ပြုပါတယ်။
enum class Priority { LOW, MEDIUM, HIGH }
data class Task(
val id: Int,
val title: String,
val priority: Priority,
val isDone: Boolean,
)
fun encode(t: Task): String = "${t.id}|${t.priority}|${t.isDone}|${t.title}"
fun decode(line: String): Task? {
val parts = line.split("|", limit = 4)
if (parts.size != 4) return null
val id = parts[0].toIntOrNull() ?: return null
val priority = Priority.entries.firstOrNull { it.name == parts[1] } ?: return null
val isDone = parts[2].toBooleanStrictOrNull() ?: return null
return Task(id, parts[3], priority, isDone)
}
fun main() {
val samples = listOf(
Task(1, "Plain title", Priority.LOW, false),
Task(2, "Title | with | pipes", Priority.HIGH, true),
Task(3, "Ünïcode and မြန်မာ", Priority.MEDIUM, false),
)
for (t in samples) {
check(decode(encode(t)) == t) { "round trip failed for $t" }
println("round trip ok: #${t.id}")
}
val bad = listOf(
"", "oops", "1|URGENT|false|x", "1|LOW|maybe|x", "x|LOW|false|x", "1|LOW|false",
)
for (line in bad) {
check(decode(line) == null) { "should reject: '$line'" }
}
println("rejected ${bad.size} bad lines")
}Check တစ်ခုခု fail ရင် program က ကိုယ်ရေးထားတဲ့ message နဲ့ ရပ်ပါလိမ့်မယ်။ တကယ့် project တွေမှာ ဒီလို assertion တွေကို kotlin.test ထဲ ရွှေ့ကြပါတယ်၊ ဒီ tutorial အစောပိုင်းက testing lesson မှာ ပါပါတယ်၊ ဒါပေမယ့် အကျင့်ကတော့ အတူတူပါ။ ရေးတဲ့ format တိုင်းအတွက် ပုံမှန် case တစ်ခု၊ ရှုပ်ထွေးတဲ့ case တစ်ခုနဲ့ မကောင်းတဲ့ input အများအပြား စမ်းပါ။
override keyword က ဘာကြောင့် မဖြစ်မနေ လိုတာလဲ
Class တစ်ခုက interface function ကို override မပါဘဲ implement လုပ်ရင် compiler က လက်မခံပါဘူး။ အောက်က snippet က တမင်မပြည့်စုံအောင် ရေးထားတာမို့ ဒီမှာ run လို့မရအောင် မှတ်ထားပါတယ်။
interface Reportable {
fun summary(): String
}
class Sprint : Reportable {
fun summary(): String = "Sprint 1"
}
fun main() {
println(Sprint().summary())
}Compile လုပ်ရင် 'summary' hides member of supertype 'Reportable' and needs an 'override' modifier ဆိုတဲ့ error နဲ့ ရပ်ပါတယ်။ Keyword က နှစ်ဖက်လုံးကို ကာကွယ်ပေးပါတယ်။ နာမည်ပဲ တူတဲ့ function နဲ့ interface function ကို မတော်တဆ ဖုံးမိတာကို တားပြီး interface က နောက်ပိုင်း override လုပ်နေတယ်လို့ ထင်တဲ့ function ကို နာမည်ပြောင်း ဒါမှမဟုတ် ဖယ်လိုက်ရင် compiler က တိုင်ပါတယ်။
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
Reportable လို interface တွေက လက်တွေ့ codebase တွေက အစိတ်အပိုင်းတွေကို အစားထိုးလို့ရအောင် ထားတဲ့ နည်းလမ်းပါ။ Payment service က PaymentGateway interface ပေါ်မှာ မှီခိုပြီး test တွေက အတုတစ်ခု ပေးပါတယ်၊ report generator ကလည်း database class အစား interface သေးသေးလေးပေါ်မှာ မှီခိုပါတယ်။ Task Manager ရဲ့ report ကို print ထုတ်တာ၊ file ထဲရေးတာ၊ e-mail ပို့တာ Reportable implementation သုံးခုနဲ့ လုပ်လို့ရပြီး summary တောင်းတဲ့ code ကို မပြောင်းရပါဘူး။
Persistence ကလည်း သင်ခန်းစာ အတူတူကို ပိုကြီးတဲ့ အတိုင်းအတာနဲ့ ပေးပါတယ်။ Data က text file၊ JSON၊ SQLite ဒါမှမဟုတ် remote API ဘယ်မှာရှိရှိ program အပြင်က ဖတ်တာ အားလုံးကို မယုံရပါဘူး။ File တွေကို လက်နဲ့ပြင်တတ်တယ်၊ format တွေက version တစ်ခုနဲ့တစ်ခု ပြောင်းတတ်တယ်၊ upload တွေက တစ်ဝက်တစ်ပျက်နဲ့ ရောက်တတ်ပါတယ်။ ဒါကြောင့် production loader တွေက record တစ်ခုချင်းစီကို စစ်ပြီး ကောင်းတာတွေ ထိန်းကာ မကောင်းတာတွေကို report လုပ်ပြီး ဘယ်နှခု ကျော်လဲ log ရေးပါတယ်၊ TaskStore.load() လိုပါပဲ။ Temporary file တွေကို temporary directory ထဲ ရေးပြီး finally မှာ ဖျက်တာကလည်း test တွေက အမှိုက်မကျန်အောင် လုပ်တဲ့ ပုံမှန်နည်းပါ။
အမှားများ
ဖြစ်လေ့ရှိတဲ့ အမှားများ
override ကို မေ့တာ
Interface function ကို override မပါဘဲ implement လုပ်ရင် warning မဟုတ်ဘဲ compile error ပါ။ 'summary' hides member of supertype 'Reportable' and needs an 'override' modifier ပါ။ Keyword ကို ထည့်ပါ၊ signature ကို မသေချာရင် IDE ကို stub generate လုပ်ခိုင်းပါ။
မမြှောက်ခင် စားတာ
done / total * 100 က Int နှစ်ခုကို အရင်စားလို့ ၃ ခုမှာ ၂ ခုပြီးရင် 0 ပေးပြီး အားလုံးပြီးတဲ့ list ကပဲ percentage ပြပါတယ်။ done * 100.0 / total လို Double နဲ့ အရင်မြှောက်ပြီး total == 0 ကို သီးခြားကိုင်တွယ်ပါ။
File ကို ယုံတဲ့ loader
split("|") နဲ့ toInt()၊ valueOf() က ပထမဆုံး ပျက်နေတဲ့ line မှာတင် throw ပြီး pipe ပါတဲ့ title က နောက်က field အားလုံးကို ရွှေ့ပစ်ပါတယ်။ Free text ကို နောက်ဆုံးမှာထား၊ limit ပါတဲ့ split သုံး၊ မအောင်မြင်တိုင်း decode() က null ပြန်ပြီး ဘယ်နှကြောင်း ကျော်လဲ report လုပ်ပါ။
Load ပြီးနောက် id ကို ပြန်စတာ
Load ပြီးနောက် repository က nextId ကို 1 ကနေ ပြန်စရင် ပထမ task အသစ်က သိမ်းထားတဲ့ task နဲ့ တိုက်ပါတယ်။ nextId ကို load လုပ်ထားတဲ့ အကြီးဆုံး id + 1 လို့ ထားပါ၊ replaceAll() လုပ်သလိုပါ၊ load ပြီးတာနဲ့ task တစ်ခုထည့်ပြီး သက်သေပြပါ။
Best Practices
Project ကို ဆက်ချဲ့ဖို့ အကြံများ
- Text file ကို JSON (kotlinx.serialization) ဒါမှမဟုတ် SQLite နဲ့ အစားထိုးပါ၊ TaskStore ရဲ့ save နဲ့ load signature ကို ထိန်းထားရင် ကျန်တာ မပြောင်းရပါဘူး။
- java.time.LocalDate နဲ့ due date ထည့်ပြီး ကျော်လွန်နေတဲ့ task တွေရဲ့ report တစ်ခု ထည့်ပါ။
- Snippet ထဲက round-trip check တွေကို kotlin.test ထဲ ရွှေ့ပြီး Gradle ကနေ run ပါ။
- main လုပ်သလိုပဲ TaskManager.execute() ကို ခေါ်တဲ့ HTTP handler သေးသေးလေး လို front end ဒုတိယတစ်ခု ထည့်ပါ။
Mini challenge
Reportable ဒုတိယတစ်ခု: sprint summary
နာမည်နဲ့ task list ကိုင်ထားတဲ့ Sprint class နဲ့ Reportable ကို ဒုတိယအကြိမ် implement လုပ်ပါ။ သူ့ summary() က task ဘယ်နှခုပြီးလဲကို round လုပ်ထားတဲ့ percentage နဲ့ ပြပြီး အလျင်မြန်ဆုံး ဖွင့်ထားတဲ့ task ကို နာမည်ပေးပါ။ Empty sprint နဲ့ အားလုံးပြီးသွားတဲ့ sprint ကို ကိုင်တွယ်ပါ။
- Sprint က Reportable ကို implement လုပ်ပြီး summary() ကို override နဲ့ မှတ်ရမယ်
- summary() က ပြီးတဲ့အရေအတွက်၊ စုစုပေါင်းနဲ့ Double division သုံးထားတဲ့ round လုပ်ထားတဲ့ percentage ကို ပြရမယ်
- နောက်ထပ် task က priority အမြင့်ဆုံး ဖွင့်ထားတဲ့ task ဖြစ်ရမယ်၊ tie ဆိုရင် id အနည်းဆုံးကို ယူမယ်
- Empty sprint က no tasks လို့ ပြပြီး ပြီးသွားတဲ့ sprint က ဘာမှ မကျန်တော့ဘူးလို့ ပြောရမယ်
- main က sprint တွေကို List<Reportable> ထဲ ထားပြီး တစ်ခုချင်းစီမှာ printSummary() ကို ခေါ်ရမယ်
// Reuse Priority, Task and Reportable from the lesson.
class Sprint(private val name: String, private val tasks: List<Task>) : Reportable {
override fun summary(): String {
// TODO: "Sprint <name>: no tasks" for an empty list
// TODO: done count, total and the rounded percentage
// TODO: the open task with the highest priority (ties: lowest id)
return ""
}
}
fun main() {
// TODO: build one normal sprint, one empty sprint and one finished sprint,
// put them in a List<Reportable> and call printSummary() on each
}ရလဒ်: Alpha က ၄ ခုမှာ ၁ ခုပြီး (25%) နဲ့ Next up: Fix crash on start ကို ပြမယ်၊ Beta က no tasks လို့ ပြမယ်၊ Gamma က ၁ ခုမှာ ၁ ခုပြီး (100%) နဲ့ sprint ပြီးသွားပြီလို့ ပြမယ်။
အရိပ်အမြွက် ကြည့်ရန်
ဖွင့်ထားတဲ့ task တွေကို filter လုပ်ပြီး sortedWith(compareByDescending<Task> { it.priority }.thenBy { it.id }) နဲ့ sort လုပ်ကာ firstOrNull() ယူပါ။ ပြီးသွားတဲ့ case အတွက် next?.title ?: ကို သုံးပြီး empty list အတွက် ဘာမှမစားခင် early return လုပ်ပါ။
အဖြေ ကြည့်ရန်
import kotlin.math.roundToInt
enum class Priority { LOW, MEDIUM, HIGH }
data class Task(
val id: Int,
val title: String,
val priority: Priority,
val isDone: Boolean = false,
)
interface Reportable {
fun summary(): String
fun printSummary() = println(summary())
}
class Sprint(private val name: String, private val tasks: List<Task>) : Reportable {
override fun summary(): String {
if (tasks.isEmpty()) return "Sprint $name: no tasks"
val done = tasks.count { it.isDone }
val percent = (done * 100.0 / tasks.size).roundToInt()
val next = tasks.filter { !it.isDone }
.sortedWith(compareByDescending<Task> { it.priority }.thenBy { it.id })
.firstOrNull()
return "Sprint $name: $done of ${tasks.size} done ($percent%)\n" +
"Next up: ${next?.title ?: "nothing, the sprint is complete"}"
}
}
fun main() {
val sprints: List<Reportable> = listOf(
Sprint(
"Alpha",
listOf(
Task(1, "Design login", Priority.MEDIUM, isDone = true),
Task(2, "Fix crash on start", Priority.HIGH),
Task(3, "Update icons", Priority.HIGH),
Task(4, "Write release notes", Priority.LOW),
),
),
Sprint("Beta", emptyList()),
Sprint("Gamma", listOf(Task(7, "Ship it", Priority.HIGH, isDone = true))),
)
sprints.forEach { it.printSummary() }
}Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Interface က class ရဲ့ ကတိကို ကြေညာပြီး default method ပါနိုင်ကာ implementation တိုင်းကို override နဲ့ မှတ်ရပါတယ်
- Report ကို groupBy၊ count နဲ့ sortedWith နဲ့ ဆောက်ပြီး tie-break ကို ရှင်းရှင်းသတ်မှတ်ကာ empty group တွေပါပြဖို့ enum entry တွေကို loop ပတ်ပါ
- မစားခင် 100.0 နဲ့ မြှောက်၊ နောက်ဆုံးမှ round လုပ်ပြီး list က empty ဆိုရင် စောစောပြန်ပါ
- File ကို ကာကွယ်ပြီးဖတ်ပါ။ Free text ကို နောက်ဆုံးထား၊ limit ပါတဲ့ split သုံး၊ မကောင်းတဲ့ line အတွက် null၊ load လုပ်ထားတဲ့ အကြီးဆုံး id ပြီးမှ id ပြန်စပါ
Kotlin language guide — Kotlin