1. Introduction
When a project grows, what breaks things most is not new code, but “new code that accidentally touched old code.” In a small educational app this shows up quickly too: you added a new command and suddenly old commands start printing “kind of differently,” and an error is output sometimes as a string, sometimes as null, sometimes as println(repo.all()) (yes, that exact style of “let Kotlin explain to the user what happened by itself”).
Fixation v1 is the moment when you say: “we have stable rules of the game.” Not “everything is perfect,” not “NASA-level architecture,” but something simple: commands return one result type, the response format is built in one place, and main becomes a predictable script of wiring and calling. This sharply reduces chaos: adding commands becomes easier, reading code becomes easier, and you’re less afraid to touch a file because it doesn’t drag half the project along with it.
To put it very down-to-earth: v1 is when your project no longer resembles a “box of wires” and starts resembling a “box of connectors.” There may be many wires, but they plug in only at strictly defined places.
The problem: “commands return whatever”
Before introducing a single contract, it helps to see the pain live. Typically beginners (and sometimes quite experienced developers after a hard day) do this: one command returns a string, another returns a Boolean, a third prints by itself, a fourth throws an exception, a fifth returns null because “well, it didn’t work.”
As a result, the CLI starts to look like a zoo of checks: here if (result != null), there try/catch, here println inside a service, there—inside a repository (that’s already a rare species, but it happens). And the worst part: you can’t tell at a glance what a command even does. You have to remember “does this command print by itself or return a string?”
We need one shared “envelope” for a command result. You can put either success or an error into it. Then the CLI always does the same thing: call the handler, get a result, print the result. No special branches per command except routing itself.
2. A single command result: sealed interface CommandResult
When you first see sealed, it seems “advanced,” but today we’ll use it very practically: as a list of allowed result variants. The idea is simple: a command is either successful (Ok) or not (Error). That’s it. No “almost worked,” “returned 0,” “it’s kinda true, but…”.
Let’s create the result type. It makes sense to keep it closer to the CLI boundary (because it’s the result of processing a command), for example in the package app.cli.contract. Important: this is not a domain model; it’s specifically a “command result for the interface.”
// FILE: app/cli/contract/CommandResult.kt
package app.cli.contract
sealed interface CommandResult {
data class Ok(val message: String) : CommandResult
data class Error(val message: String) : CommandResult
}
Notice a detail: both Ok and Error contain message. This is very useful discipline for v1: every result has a human-readable explanation. In future versions you can make it more complex (for example, add data), but in v1 we need to achieve stability and simplicity.
3. Centralized formatting
If you’ve ever changed message text across a project, you know this quest: “find all places where ERROR is printed.” Search usually works, but then you find one more place where println("Err: ...") was printed. And another. And another…
In v1 we do it like this: result formatting lives in one place. The CLI calls render() and prints the string. The format can be changed centrally, and all commands automatically start looking the same.
// FILE: app/cli/contract/CommandResultRender.kt
package app.cli.contract
fun CommandResult.render(): String =
when (this) {
is CommandResult.Ok -> "OK: $message"
is CommandResult.Error -> "ERROR: $message"
}
Exhaustiveness of when matters here. We don’t write else. Why? Because a sealed interface promises: the number of variants is finite. If you later add a new variant (for example, Help or Exit), the compiler will say: “hey, you forgot to handle one more case.” This is the perfect “guard” at the entrance to changes: it won’t let you make the system incomplete.
4. A single command handling contract: handle(...) -> CommandResult
Now we need an object (or a function) that takes a parsed command and returns CommandResult. This is the v1 “public entry point” for the CLI: you pass a string to the parser, then the parser passes a structure to the handler, and the handler returns the result.
First, let’s fix the parsed-command model. We’re not making a complex parser; it’s enough to have the command name and a string argument.
// FILE: app/cli/parse/ParsedCommand.kt
package app.cli.parse
data class ParsedCommand(
val name: String,
val arg: String?
)
Now a simple parsing function. Here we’re not trying to build an “ideal CLI,” we’re just making a stable agreement: the command is a word, the argument is everything else.
// FILE: app/cli/parse/CommandLineParser.kt
package app.cli.parse
fun parseCommandLine(line: String): ParsedCommand {
val s = line.trim()
val space = s.indexOf(' ')
return if (space == -1) ParsedCommand(s.lowercase(), null)
else ParsedCommand(s.substring(0, space).lowercase(), s.substring(space + 1).trim().ifEmpty { null })
}
Yes, the line is a bit long, but the logic is simple: normalize the command name (lowercase()), cut the argument, and turn an empty string into null. This is very convenient later: arg == null means “there is no argument.”
And now—the command handler. It uses the domain service and exporter (which we already built in previous lectures), but outwardly it returns only CommandResult.
// FILE: app/cli/CommandHandler.kt
package app.cli
import app.cli.contract.CommandResult
import app.cli.parse.ParsedCommand
import domain.service.ExpenseService
import domain.service.ReportExporter
class CommandHandler(
private val service: ExpenseService,
private val exporter: ReportExporter
) {
fun handle(cmd: ParsedCommand): CommandResult =
when (cmd.name) {
"list" -> CommandResult.Ok(service.report(exporter))
else -> CommandResult.Error("Unknown command: ${cmd.name}")
}
}
So far we implemented only "list" to keep the example small. But the most important thing here is the shape: every path returns CommandResult. Even an unknown command is not an exception, not null, not printing right here, but a normal Error(...).
5. How the layers look together: wiring dependencies in main
In main we don’t want business logic. We want a script: build dependencies → read a command → parse → handle → render → output. This is the case when a “simple program” becomes a sign of order, not primitiveness.
Let’s show a minimal main that processes one command. In a real project you’ve probably already made a loop, but right now it’s important to see the whole v1 structure end-to-end.
// FILE: app/cli/Main.kt
package app.cli
import app.cli.contract.render
import app.cli.parse.parseCommandLine
import storage.InMemoryExpenseRepository
import domain.service.ExpenseService
import domain.service.PlainTextExporter
fun main() {
val handler = CommandHandler(ExpenseService(InMemoryExpenseRepository()), PlainTextExporter())
val result = handler.handle(parseCommandLine(readln()))
println(result.render()) // OK: ... or ERROR: ...
}
Yes, the handler wiring line looks dense. That’s normal for v1. We deliberately don’t introduce dependency containers and “magic wiring.” What matters is something else: main knows nothing about expense rules and report formats; it just connects parts like a LEGO set (sometimes painfully stepping on bricks).
If you want to add a loop, it will stay “thin” as well:
// FILE: app/cli/MainLoop.kt
package app.cli
import app.cli.contract.render
import app.cli.parse.parseCommandLine
fun runLoop(handler: CommandHandler) {
while (true) {
val result = handler.handle(parseCommandLine(readln()))
println(result.render()) // single response format
}
}
There is no "exit" command yet—that’s fine. We’re fixing the result contract, not building a perfect terminal.
6. Why Ok/Error is a stable API
At this stage it’s useful to take a small “architecture pause.” It may look like we wrote just two small data classes and one extension function. But in terms of effect it’s like finally labeling circuit breakers in your panel: electricity existed before too, but now you don’t accidentally turn off the fridge when you meant to turn off the hallway light.
Here’s what stabilizes Ok/Error:
From the caller’s point of view (CLI) there’s no longer a variety of results. You don’t need to remember “what the command returned.” You always get one type and always render it the same way.
From the project growth point of view, new commands are added predictably. You don’t smear messages across main and you don’t breed println in unexpected places. If you add an "add" command, it will also return Ok/Error.
From the compiler’s point of view, you get a “completeness insurance.” sealed + when without else is your free static audit: the compiler forces you to handle all variants.
To reinforce the idea, it’s useful to see the pipeline diagram once:
flowchart LR
A[readln] --> B[parseCommandLine]
B --> C[CommandHandler.handle]
C --> D[CommandResult]
D --> E[render]
E --> F[println]
This is a good sign that “v1 is assembled”: the steps are clear, and each step is responsible for its own part.
And now a very important point about “v1 quality criteria.” This is not a list for the sake of a list; it’s a way to quickly check that the structure holds up when you’re tired and want to “just finish the feature.” If your domain layer doesn’t use readln() and println(), storage is hidden behind an interface, the exporter returns a string, and main looks like a script, then you really did lock down the boundaries rather than just spreading files across folders.
7. A small practical nuance
Sometimes there’s a temptation to be “smarter”: the "list" command returns a report string, the "add" command returns a Boolean, the "help" command returns a list of strings… and so on. It seems “more type-safe” (each command is “unique,” right?). But at the CLI level it turns into the need to distinguish commands one more time: “if this is list—print like this, if add—otherwise.”
A single result is a compromise for the sake of robustness. We say: at the CLI level we care about one thing—did it work or not, and what message to show. Inside the domain you can return any structures you want, but at the command boundary we bring everything to a single form.
In v1 this is especially useful because you’re not building complex interfaces yet. You have a console, and a console likes simple rules: one command—one line of response, and preferably no surprises.
For a visual comparison, you can keep this table in mind:
| Approach | What commands return | What happens in the CLI |
|---|---|---|
| “Each command does what it wants” | String, Boolean, null, printing inside | many special cases |
| Single v1 contract | CommandResult | one processing script |
And yes, if it seems to you that this is “too simple,” congratulations: you started valuing simplicity as an engineering tool. It’s a dangerous path—next you’ll start naming variables properly and stop writing x1, x2, x3. There’s almost no way back.
8. Typical mistakes when fixing v1 and using Ok/Error
Mistake #1: commands still print inside themselves, and CommandResult appears “just for show.”
This happens often: you added CommandResult, but println("Added!") still lives in ExpenseService. As a result, the message prints twice, or prints in an unexpected place, or the “OK/ERROR” format isn’t followed. The fix is simple and a bit painful: remove println from domain and storage, and force yourself to return data/result outward. The CLI prints; the other layers do not.
Mistake #2: people write when over sealed with else “so it always compiles.”
else looks like a safety cushion, but in reality it’s an alarm switch-off. While everything is fine—you won’t notice. But when you add a new result variant, the compiler will no longer help you find the places where you forgot to handle it. In v1 it’s better to discipline yourself: if it’s sealed, handle variants explicitly, without else.
Mistake #3: CommandResult starts being used as a “bag for everything,” and half the domain model ends up in it.
Sometimes you want to put not a string into Ok but a list of expenses, a sum, statistics… and suddenly CommandResult turns into a new layer of the domain model, just with a different name. In v1 keep the contract narrow: message: String. If you really want data—let the domain return data, let the exporter produce a string, and let the command return that string in Ok.
Mistake #4: the command handler starts directly poking into the repository or keeps state that should live in the domain.
If CommandHandler suddenly starts doing repo.items.add(...) or validates amounts itself, the boundary has drifted: the CLI command became a “half-domain.” In v1 it’s better to patiently keep roles: the handler routes and calls the service, the service applies rules, the repository stores, the exporter formats.
Mistake #5: different commands use different message styles because they format strings “somewhere along the way.”
Today you wrote "OK: ..." in one place, tomorrow—"Success: ..." in another. The user sees inconsistency, and you spend time on cosmetics instead of logic. In v1 this is solved by centralized render() and the habit that everything printed to the user goes through a single formatting point.
Mistake #6: main stops being a script and grows logic again—only now “in pretty packages.”
This is a tricky regression: you arranged files, introduced interfaces, and then main ended up with 60 lines of conditions and handling. A sign of a healthy v1: main reads top-to-bottom like a recipe. If the recipe turns into a novel, it’s time to push responsibility back into handler/service/exporter.
GO TO FULL VERSION