1. Introduction
Almost everyone starts the same way: they take main, put readln() inside, a couple of ifs, an expense list, a couple of commands (add, list, remove)—and enjoy life. And that’s a normal stage: you’re learning, you want to see results quickly, and println() gives a nice dopamine hit. But then the typical story happens: more commands, more checks, “let’s tweak output formatting just a bit”—and main turns into a “spaceship command centre” where you simultaneously have the steering, the engine, the kitchen, and the cat.
Let’s sketch the typical “everything in one place” approach (it’s not “a bad person wrote this”, it’s “this is how we grow”):
fun main() {
val expenses = mutableListOf<String>()
while (true) {
print("> ")
val line = readln().trim()
if (line == "exit") break
if (line.startsWith("add ")) {
val title = line.removePrefix("add ").trim()
expenses.add(title)
println("Added: $title") // Added: Coffee
} else if (line == "list") {
println(expenses.joinToString())
} else {
println("Unknown command")
}
}
}
At first it feels like: “well, OK, readable enough”. And then you want, for example, each expense to have an amount, the amount to be positive, whitespace in titles to be cleaned consistently, output to look nicer, and totals to be calculated. And suddenly you realize that:
- input is mixed with rules (validation/normalization),
- rules are mixed with storage (we directly poke into MutableList),
- output is mixed with everything else,
- and any small change feels scary: what if we break the add command, and along with it list, because we “reused a variable just a little bit”.
Main idea: when everything is in main, every new feature adds chaos not linearly, but avalanche-style.
2. Three roles: CLI, domain, storage
Now we’ll introduce three concepts. They sound “grown-up”, but mean a very simple thing: who is responsible for what. Imagine a small cafe:
- one person takes the customer’s order,
- another cooks,
- a third manages inventory/ingredient accounting.
If one person does everything at once, either they’re a hero, or their health will run out soon (more likely the second). In a program it’s similar: we need “distributed work”.
The roles in our console project are:
| Role | What it does | What it must not do |
|---|---|---|
| CLI (Command Line Interface) | Reads a line, understands a command, prints a response | Does not store business rules; does not decide “right/wrong” in substance |
| Domain (business logic) | Knows the rules: what an expense is, what checks are needed, how to compute totals | Does not call readln() and does not do println() |
| Storage (persistence) | Stores and returns data (in v1—just in memory) | Does not parse commands and does not decide business rules |
It helps to keep a simple data-flow diagram in mind:
flowchart LR
U[User] --> CLI[CLI: read/parsed]
CLI --> D[Domain: applied rules]
D --> S[Storage: saved/returned data]
D --> CLI
CLI --> U
And the key rule of the day: domain code must be callable without the console. That is, in theory, tomorrow we could make not a console but, for example, a GUI—and the domain would almost not change. (We won’t build a GUI, but the idea is useful.)
3. Practical example: expense tracking
Domain model: “clean data”
Before we split responsibilities, we need to agree on what we actually store. Earlier we could store an expense as a string, or as Pair<String, Int>, or as “well, in a string separated by ;”. Today we’ll take a step toward a proper model: an expense is an object with clear fields.
Important: a domain model is not “logic”; it’s “domain data”. It should be as simple and “clean” as possible: no input reading, no printing, no formatting.
data class Expense(
val title: String,
val amount: Int
)
There’s a small but fundamental point here: when you see Expense(title, amount), you should no longer have to remember “what is in .first, and what is in .second”. You read it like a human.
If you feel like adding category, createdAt, and so on—hold on. Today we’re practicing separation of concerns, not building “perfect accounting”.
Storage: in-memory repository
When people hear “storage”, they often imagine a database, migrations, transactions, and mild panic. Today it’s simpler: the storage layer in version v1 is a class that hides a list inside and provides “add” and “get all” methods.
Why do we need a separate class if we can just do mutableListOf() in main? Because we want “how we store things” to be a separate detail, not smeared across the whole program.
Notice something important: externally we return a List<Expense>, not a MutableList<Expense>. This habit saves nerves: whoever gets a List cannot “silently” delete an element and leave you with a mysterious bug. In Kotlin this directly matches the idea of read-only collection interfaces.
class ExpenseStorage {
private val items = mutableListOf<Expense>()
fun add(expense: Expense) {
items.add(expense)
}
fun all(): List<Expense> = items
}
Note: there is neither readln() nor println() here. Storage is silent, like a good refrigerator: it doesn’t comment on your decisions.
Domain: a service with rules, but without printing
The domain layer is where the “rules of the game” live. If CLI is “how to talk to the user”, then domain is “what counts as a valid expense”. This is exactly where require, checks, and string normalization belong.
Now we’ll make an ExpenseService that accepts ready values (title, amount), normalizes them, and saves via storage.
class ExpenseService(
private val storage: ExpenseStorage
) {
fun addExpense(title: String, amount: Int) {
val normalizedTitle = title.trim()
require(normalizedTitle.isNotEmpty()) { "Title must not be empty" }
require(amount > 0) { "Amount must be > 0" }
storage.add(Expense(normalizedTitle, amount))
}
fun listExpenses(): List<Expense> = storage.all()
}
There are two important ideas here.
First: the domain accepts already prepared values, not “a raw command string”. That is, ExpenseService should not parse "add coffee 200". That’s the CLI’s job.
Second: the domain does not print “Added!” and does not ask the user “enter an amount”. It either performs the operation or reports an error via an exception (that’s how we’ll do it today; later we’ll move to more “controlled” results, but that’s the next part).
CLI: read a line, parse a command, call the domain
The CLI layer is a “translator” between a human and the program. A human writes strings; the domain wants normal parameters. So the CLI must do three steps: read, parse, call.
readln() and println() live here—that’s normal and expected.
Let’s make a small command model and the simplest parser. Note: the code is small and straightforward, no magic—we care about readability.
data class ParsedCommand(
val name: String,
val args: String
)
fun parseCommand(line: String): ParsedCommand {
val trimmed = line.trim()
val space = trimmed.indexOf(' ')
return if (space == -1) {
ParsedCommand(name = trimmed.lowercase(), args = "")
} else {
val name = trimmed.substring(0, space).lowercase()
val args = trimmed.substring(space + 1).trim()
ParsedCommand(name = name, args = args)
}
}
Now the CLI logic: we read a line, parse it, do a when on the command name, and then call the service.
For now, we’ll implement two commands:
- add <title>;<amount>
- list
- exit
Why use ;? Because the title may contain spaces, and we need an easy way to separate the amount. This is not an “ideal format”, it’s simply “convenient for a learning example”.
fun main() {
val storage = ExpenseStorage()
val service = ExpenseService(storage)
while (true) {
print("> ")
val cmd = parseCommand(readln())
if (cmd.name == "exit") break
when (cmd.name) {
"add" -> handleAdd(cmd.args, service)
"list" -> handleList(service)
else -> println("Unknown command: ${cmd.name}")
}
}
}
Here main already starts looking like a script: “read → parse → pass it along”. And that’s a very good sign.
All that’s left is to implement handleAdd and handleList. Note: this is still the CLI layer, so printing here is allowed.
fun handleAdd(args: String, service: ExpenseService) {
val parts = args.split(';', limit = 2)
val title = parts.getOrNull(0)?.trim().orEmpty()
val amount = parts.getOrNull(1)?.trim()?.toIntOrNull() ?: 0
try {
service.addExpense(title, amount)
println("OK: added") // OK: added
} catch (e: IllegalArgumentException) {
println("ERROR: ${e.message}") // ERROR: Amount must be > 0
}
}
We intentionally catch IllegalArgumentException, because require(...) throws exactly that. This is “soft” handling: the program doesn’t crash; it explains to the user what is wrong.
handleList:
fun handleList(service: ExpenseService) {
val items = service.listExpenses()
if (items.isEmpty()) {
println("(empty)") // (empty)
return
}
for ((index, e) in items.withIndex()) {
println("${index + 1}. ${e.title} — ${e.amount}")
}
}
Formatting the list is a CLI task. The domain should return data, and the CLI decides how to display it nicely.
Where the boundary between layers is
When you start splitting code by roles, a subtle problem appears: “can I just bend the rules a little here, it’s only one println()?”. You can. Right up until you have ten “only one println”.
To keep the boundary from creeping, it helps to remember a few “anti-signals”.
- If you see readln() inside a service, it’s almost always a design mistake. readln() is about the console, and the console is CLI. The domain must be able to work without a human sitting next to it.
- If you see println() inside storage, that’s also a signal: storage should not “comment on life”. It should store and return.
- If you return a MutableList to the outside, then any external code can call clear(), and then you’ll be looking for “who ate my data”. Kotlin collections explicitly distinguish read-only and mutable interfaces, and that distinction is worth using as a protective fence.
Sometimes it feels like “there’s no difference, I’m writing the code alone anyway”. There is. The difference is you in two weeks, opening the project, with a different life in your head, different tasks, and zero desire to solve riddles made out of main.
4. Common mistakes when splitting into CLI / domain / storage
Before we finish, let’s walk through the rakes that almost everyone steps on (I stepped on them too, don’t worry—it’s a tradition, like the programmer tradition of creating one more “final” file named final_final2.kt).
Mistake #1: the domain starts printing to the console.
Usually it looks harmless: “I just want to print println("Added!") right inside addExpense”. But then the domain becomes dependent on the console; later you’ll want different output (for example, a one-line report or no output at all), and you’ll have to dig println out of the logic. The correct idea: the domain either returns data or reports an error, and printing is the CLI’s responsibility.
Mistake #2: the domain reads input (readln()) “for convenience”.
It’s tempting: “let the service ask for the amount itself”. But then the service cannot be used without an interactive console (for example, from another UI), and it becomes unclear where the scenario control even lives. readln() is strictly a CLI tool, and it belongs there.
Mistake #3: storage is exposed as a public val items: MutableList<Expense>.
People often do this “for simplicity”, and then some random CLI code does items.removeAt(0) and the logic breaks. Storage should hide mutability inside itself and return List externally. This supports the idea of read-only collection interfaces and protects against accidental mutation.
Mistake #4: the CLI starts applying business rules.
For example, in handleAdd you decide that “amount must be > 0” and you check it in CLI, but forget to do it in the domain. Later another way of adding will appear (another command, import, anything), and some rules will exist only in one place. Business rules must live in the domain, and the CLI should be a “translator”, not a “judge”.
Mistake #5: mixing normalization and presentation.
A very common thing: the title string is trimmed (trim()) only when printing in println, because “it looks nicer”. But it’s better to normalize data at the entry point into the domain (as we did), so inside the program the data is always in one format. Then output is just output, without attempts to “patch” the meaning.
Mistake #6: trying to build “perfect architecture” too early.
There’s an opposite extreme: someone reads the word “architecture” and urgently decides to make 25 classes, 12 interfaces, and a diagram they’re afraid of themselves. Today the goal is more modest: separate input/output from rules and from storage. If you can explain where CLI is, where domain is, and where storage is, you’re already doing great—and the code will become noticeably calmer.
GO TO FULL VERSION