1. Interface nhu ranh gioi giua cac layer
Ban co the viet ung dung ma khong can interface, va no van chay. Giong nhu ban co the di xe dap khong can buong tay — doi khi van duoc, cho den khi gap o ga. Interface khong phai de “cho dep”, ma de bao ve code khoi su hon loan cua thay doi: khi ban doi cach luu tru hoac dinh dang bao cao, ban khong muon logic lenh, service, in an va nua du an bi vo tung toe chi vi mot sua doi.
Hay tuong tuong ta co du an “quan ly chi tieu” (mot mini-tracker tuong trung). O cap domain ta muon co kha nang:
- them mot khoan chi tieu kem cac kiem tra,
- lay danh sach cac khoan chi tieu,
- tao bao cao dang van ban.
Nhung cu the chi tieu duoc luu nhu the nao (trong list, map, cache, file — chua can hom nay) va cu the bao cao trong ra sao (plain text, bang, CSV — cung chua can hom nay) — deu la chi tiet ma ban se thuong xuyen muon thay doi.
Interface trong cau chuyen nay giong nhu “o cam”: ban khong can biet nha may dien van hanh the nao de cam laptop vao su dung.
Interface nhu mot hop dong
Rat quan trong la khong bien interface thanh “god object” lam duoc moi thu. Mot interface tot la mot hop dong: it phuong thuc, nhieu ro rang. No tra loi cau hoi: “Code goi can gi?” — va bo qua cau hoi: “Them gi do de phong truong hop tuong lai thi hay?”.
Co mot cai bay kinh dien cho nguoi moi: ban viet InMemoryExpenseRepository, roi tao interface ExpenseRepository co do “rong” y het implementation, ke ca cac phuong thuc phu tro. Ket qua: interface khong con la hop dong, ma la “anh chup cua implementation”. Khi do no khong con bao ve he thong: bat ky mong muon moi nao trong implementation se keo theo thay doi interface, va keo theo thay doi o tat ca cac layer.
Ghi nho quy tac sau:
Interface khong phai la danh sach kha nang cua ban. Interface la danh sach nhu cau cua nguoi khac.
Mo hinh domain
Truoc khi viet repository va exporter, ta can mo hinh du lieu. Mo hinh trong domain nen don gian toi da: chi la du lieu, khong them gi khac.
// FILE: domain/model/Expense.kt
package domain.model
data class Expense(
val title: String,
val amount: Int,
)
O day khong co println, khong co readln, khong co dinh dang, khong co luu tru. Chi co y nghia: “khoan chi tieu la ten va so tien”.
2. Repository: contract truy cap du lieu domain
Repository (Repository) la “diem vao” de lam viec voi du lieu. O muc do cua chung ta (v1) no chi la contract: cach them mot khoan chi tieu va cach lay danh sach cac khoan chi tieu. Khong co gi sieu phuc tap.
Quan trong: repository khong nhat thiet la database. Hom nay no co the chi la mot list trong bo nho. Y nghia khong nam o cho noi du lieu nam, ma nam o cho domain-code khong duoc phu thuoc vao cach luu tru cu the.
Interface ExpenseRepository: hep va “chan” — the la tot
Ta lam contract toi thieu: add() va all().
// FILE: domain/service/ExpenseRepository.kt
package domain.service
import domain.model.Expense
interface ExpenseRepository {
fun add(expense: Expense)
fun all(): List<Expense>
}
Tai sao all() tra ve List, khong phai MutableList? Vi ta muon dua ra ben ngoai “goc nhin chi-doc”, de code ben ngoai khong the “vo tinh” xoa du lieu truc tiep.
Trong Kotlin co mot y tuong thuc dung quan trong: MutableList la list co cac thao tac thay doi, con List la “chi doc”. Ke ca khi ben trong dang dung list co the thay doi, ben ngoai van nen nhan duoc interface chi-doc. Dieu nay phu hop voi cach tiep can chung cua collection trong Kotlin: co cac kieu read-only va mutable; voi mutable thi co cac thao tac sua doi.
Implementation InMemoryExpenseRepository: giau MutableList vao ben trong
Gio ta viet kho luu trong bo nho. Day la storage-layer, nhung no implement contract cua domain.
// FILE: storage/InMemoryExpenseRepository.kt
package storage
import domain.model.Expense
import domain.service.ExpenseRepository
class InMemoryExpenseRepository : ExpenseRepository {
private val items = mutableListOf<Expense>()
override fun add(expense: Expense) {
items.add(expense)
}
override fun all(): List<Expense> = items
}
Hay chu y mot chi tiet: items la private. Day khong phai “tieu tiet”, ma la bao ve khoi ro ri trach nhiem. Neu items la public, CLI co the lam repo.items.clear() va “pha het moi thu mot cach hop le, khong can canh bao”.
Tieu tiet: “read-only List” khong co nghia la “doi tuong bat bien”
O day co mot diem tinh te trong Kotlin: neu ban tra ve items duoi dang List, dieu nay gioi han nguoi goi o muc type (ho khong the goi add()), nhung no van la cung mot collection, chi khac “goc nhin” (view) la khac.
Doi khi nhu the la on (va trong du an hoc tap v1 — on). Nhung doi khi ban muon tra ve “snapshot” (toList()), de code ben ngoai hoan toan khong the anh huong den trang thai cua ban, ke ca mot cach gian tiep.
Co the lam nhu sau:
override fun all(): List<Expense> = items.toList()
Cach nay an toan hon ve mat dong goi (encapsulation), nhung ton bo nho/thoi gian hon. Voi v1, ta thuong giu phuong an don gian, nhung can hieu rang co su lua chon.
3. Domain-service
Bay gio ta gom logic “the nao la mot khoan chi tieu hop le” vao mot noi. Service khong in, khong doc input, khong luu du lieu truc tiep — no ap dung quy tac va goi repository.
// FILE: domain/service/ExpenseService.kt
package domain.service
import domain.model.Expense
class ExpenseService(private val repo: ExpenseRepository) {
fun add(title: String, amount: Int) {
val normalizedTitle = title.trim()
require(normalizedTitle.isNotEmpty()) { "Title must not be empty" }
require(amount > 0) { "Amount must be > 0" }
repo.add(Expense(normalizedTitle, amount))
}
fun all(): List<Expense> = repo.all()
}
O day can nhin ra “hinh hoc” phu thuoc cua kien truc:
- ExpenseService phu thuoc vao interface ExpenseRepository,
- implementation cu the (InMemoryExpenseRepository) se duoc gan tu ben ngoai, trong CLI,
- service khong biet va khong nen biet du lieu duoc luu o dau va nhu the nao.
Day chinh la dependency injection qua constructor (constructor injection) o dang co ban nhat, “thu cong”.
4. Exporter: contract rieng cho dinh dang bao cao
Gio toi ranh gioi thu hai — bao cao. Thuong nguoi moi lam the nay: service tao chuoi, roi con tu in ra. Hoac CLI tu ghep bao cao thu cong. Ca hai cach deu tao ra su rang buoc khong can thiet.
Logic dinh dang la mot trach nhiem rieng: “chuyen du lieu thanh van ban”. Chung ta co tinh lam sao de exporter tra ve String, khong phai tu println. Vi sao? Vi in an la layer CLI, con dinh dang la mot vai tro rieng co the tai su dung.
Interface ReportExporter
// FILE: domain/service/ReportExporter.kt
package domain.service
import domain.model.Expense
interface ReportExporter {
fun export(expenses: List<Expense>): String
}
Interface lai tiep tuc “hep”: mot method, mot nhiem vu. No khong biet ve console, khong biet ve command, khong biet ve repository. Duoc dua du lieu vao — no tra ve text.
Implementation PlainTextExporter: bao cao van ban don gian
// FILE: domain/service/PlainTextExporter.kt
package domain.service
import domain.model.Expense
class PlainTextExporter : ReportExporter {
override fun export(expenses: List<Expense>): String {
return expenses.joinToString(separator = "\n") { e ->
"${e.title}: ${e.amount}"
}
}
}
Exporter nay tao format thang thung nhat co the. Va nhu the la tot: khi ban lam kien truc, nen bat dau tu format don gian de nhin ro cac ranh gioi.
Them mot implementation nua: “bang” can le
Doi khi ban muon bao cao trong gon gang hon. Ta co the lam exporter thu hai ma khong doi service va khong doi repository.
// FILE: domain/service/TableTextExporter.kt
package domain.service
import domain.model.Expense
class TableTextExporter : ReportExporter {
override fun export(expenses: List<Expense>): String {
return expenses.joinToString(separator = "\n") { e ->
val title = e.title.padEnd(20, ' ')
val amount = e.amount.toString().padStart(6, ' ')
"$title | $amount"
}
}
}
Hieu ung quan trong: ban co the doi format bao cao bang mot lan thay implementation trong CLI (ta se lam o duoi), ma khong can viet lai phan con lai cua he thong.
5. Cach moi thu duoc ket noi: CLI lap rap cac phu thuoc
Loi hay gap nhat o giai doan nay la “keo moi thu ve lai main”. Vi vay ta giu main ngan gon: no tao repository, service, exporter va goi cac thao tac.
// FILE: app/cli/Main.kt
package app.cli
import domain.service.ExpenseService
import domain.service.TableTextExporter
import storage.InMemoryExpenseRepository
fun main() {
val repo = InMemoryExpenseRepository()
val service = ExpenseService(repo)
val exporter = TableTextExporter()
service.add("Coffee", 200)
service.add("Taxi", 500)
println(exporter.export(service.all()))
// Coffee | 200
// Taxi | 500
}
Hay de y: CLI lam println, vi do la viec cua no. Exporter tra ve chuoi. Service ap dung quy tac. Repository luu lai. Moi thanh phan co vai tro rieng, khong ai “xam pham lanh dia” cua nguoi khac.
6. Vi sao “API hep” khong phai kho tinh, ma la bao ve khoi van de tuong lai
Luc nay ban se muon them vao ExpenseRepository du thu: remove, update, findByTitle, clear, count, totalAmount va “them cai nay nua, sau nay se can”. Nhung nhu vay se bien interface thanh “trung tam vu tru”, va moi layer bat dau phu thuoc vao qua nhieu chi tiet.
Thay vao do, ta giu interface toi thieu, con cac thao tac phuc tap thi bieu dien hoac bang cac method rieng cua service (domain-rules), hoac bang cac bao cao (exporters).
Ben duoi la bang nho de cuong co truc giac.
| Cau hoi | Tra loi te | Tra loi tot |
|---|---|---|
| “Dat println o dau?” | “Trong exporter, vi no lien quan bao cao” | “Trong CLI: exporter tra ve String” |
| “Ai nen trim ten?” | “CLI, vi o do co input” | “Service: do la quy tac domain” |
| “Co the tra ve MutableList ra ben ngoai khong?” | “Co, nhanh hon ma” | “Khong, ben ngoai la List, mutation bi an ben trong” |
| “Co can all() lam toList() khong?” | “Luc nao cung can, vi dep” | “Doi khi can: do la snapshot, nhung co gia phai tra” |
7. So do phu thuoc: ai co quyen biet ve ai
De dau khong bien thanh trinh bien dich Kotlin (du nghe cung la mo uoc cua mot so nguoi), nen giu trong dau mot buc tranh:
flowchart TD
CLI[app.cli<br/>readln/println/commands]
SERVICE[domain.service<br/>rules and use cases]
MODEL[domain.model<br/>data types]
REPO[domain.service.ExpenseRepository<br/>contract]
EXPORT[domain.service.ReportExporter<br/>contract]
STORAGE[storage<br/>InMemoryExpenseRepository]
CLI --> SERVICE
CLI --> EXPORT
SERVICE --> MODEL
SERVICE --> REPO
STORAGE --> REPO
EXPORT --> MODEL
Y nghia: CLI co the lap rap he thong tu cac manh ghep va goi cac use case. Domain giu rules va contract. Storage implement contract. Exporter implement contract. Nhung domain khong duoc “import CLI”, neu khong cac layer se bi tron lan.
8. Loi thuong gap
Loi №1: interface “de phong” tro nen khong lo.
Thuong no trong nhu sau: ban viet InMemoryExpenseRepository, thay co the “neu muon” thi xoa, clear, sort, tinh tong — va ban them het vao ExpenseRepository. Sau do CLI dung nua so method, service dung nua con lai, va ban khong the doi implementation repository ma khong viet lai ca du an. Cach chua tri rat “chan”, nhung hieu qua: chi giu lai trong interface nhung method ma code goi thuc su khong the thieu.
Loi №2: repository “ro ri ra ngoai” thong qua MutableList.
Khi all() tra ve MutableList, code ben ngoai co quyen thay doi trang thai ben trong repository truc tiep. Dieu nay pha vo invariant cua service: service co the kiem tra amount > 0, nhung sau do ai do trong CLI co the them khoan chi tieu co -100 truc tiep vao list. Vi vay, ben ngoai nhan List, ben trong luu MutableList. Trong Kotlin dieu nay phu hop voi mo hinh read-only va mutable collections.
Loi №3: exporter tu in (println nam trong export).
Neu exporter tu in, no tro thanh “mot nua CLI”, va con khong the tai su dung tot: ban khong the lay chuoi bao cao de, vi du, chen vao mot thong diep khac. Gi vung quy tac: exporter tra ve String, con viec in la trong CLI.
Loi №4: service tu tao repository ben trong (val repo = InMemoryExpenseRepository()).
Khi do service bi “dong dinh” voi mot implementation luu tru cu the. Tuong nhu chi la tieu tiet, nhung no giet ngay y nghia cua interface. Service phai phu thuoc vao contract (ExpenseRepository) va nhan implementation qua constructor. Khi do CLI co the “thay the” implementation khac ma khong can doi domain-code.
Loi №5: hieu all(): List<Expense> = items nhu la “bao ve tuyet doi khoi thay doi”.
Read-only List dung la gioi han truy cap cac thao tac thay doi, nhung no van co the la “view” cua cung mot collection. Doi khi nhu vay la du, doi khi ban muon tra ve ban sao (toList()), tuc la snapshot du lieu. Kotlin nhan manh su khac biet giua viec copy collection va viec tao them mot tham chieu toi cung collection.
GO TO FULL VERSION