CodeGym /Courses /Kotlin SELF /How to lock architecture into the project structure

How to lock architecture into the project structure

Kotlin SELF
Level 39, Lesson 1
Available

1. Introduction

When a project is small, it feels like folders and packages are “for big scary enterprises,” while we just want to finish the add command and go have some tea. The problem is that project growth happens quietly: today it’s 3 files, tomorrow it’s 12, and a week later you’re searching for “where do we parse the command,” only to discover 4 parseCommand functions that differ by exactly one space.

Packages in Kotlin are a way to name the “neighborhoods” of your project: CLI lives here, domain logic lives here, storage lives here. And when you follow the rule of “who is allowed to import whom,” the structure starts working like a guardrail on a staircase: it doesn’t get in your way, but it helps a lot to keep you from falling.

Kotlin technically does not require disk folders to match the package name: files can be placed “anywhere.” But the human brain is not a compiler, and it really likes it when domain/model/Expense.kt actually contains the package domain.model. That’s why in practice it’s almost always worth keeping the directory structure aligned with packages: navigation is easier, imports are clearer, and you get fewer accidental mistakes when moving files around.

You can think of it this way: the compiler doesn’t care where a file lives, but a person does. We write code for people (and a little bit for the compiler, so it doesn’t cry).

2. Remembering package and import

In Kotlin, the package declaration is written at the top of the file, and imports come right after it. This is not just a tradition “because that’s how it’s done”: it makes the file readable top-down—first the address (package), then dependencies (imports), then the code.

At the same time, Kotlin technically does not require disk folders to match the package name: files can be placed “anywhere.” But for a team and an IDE, it’s much calmer when the directory structure mirrors the package structure, especially in JVM projects alongside Java.

Mini example: a package as a file “address”


package domain.model

data class Expense(val title: String, val amount: Int)

Everything is honest here: the file says “I’m from the domain.model neighborhood.” If we want to use Expense in another package, we’ll have to import it.

3. Package structure: fixing responsibility

For packages to work as an architectural hint, their names must reflect responsibility. Let’s agree on a simple, readable structure that helps keep boundaries:

Layer (responsibility) Package What lives here What must not be here
CLI
app.cli
reading commands, parsing input, printing, program flow business rules and “whatever” data storage
Domain (model)
domain.model
data class
es of the domain
readln()
,
println()
, commands, UI formatting
Domain (rules/operations)
domain.service
validation, normalization, operations on models direct console work
Storage
storage
storing and retrieving data (in memory) command parsing and console output

This layout is intentionally very simple. What matters is that with a single glance at a package you can tell: “this is part of the scenario” or “this is part of the domain logic.”

4. Dependency direction: who imports whom

This is where real architecture begins, even if the project is still small. Dependency direction is the rule of “who depends on whom.” In code, it shows up literally: which packages we write import statements to which packages.

We want the outer layer (CLI) to depend on the inner one (domain), not the other way around. Then the domain can be reused anywhere: in tests, in another UI, with another way of entering commands. Even if you’re not doing any of that yet, simply having the option makes the code feel steadier.

Diagrammatically (a map of allowed imports) it looks like this:

flowchart TD
    CLI[app.cli] --> DS[domain.service]
    CLI --> DM[domain.model]
    CLI --> ST[storage]
    DS --> DM
    ST --> DM

    %% important constraint:
    %% domain does NOT depend on app.cli

If you simplify it to one rule: domain.* does not import app.cli.*. Ever. Not even “just one tiny printHelp() function.” Because it’s not a “tiny function,” it’s a hole in the boundary.

Why this matters in a real project

If domain starts importing CLI, you’ll get a “conceptual circular dependency”: you won’t be able to tell where domain rules end and the interface begins. At some point, any change will require changes everywhere at once—and the project will become fragile.

5. Practical example: laying out code by packages

Now we’ll take our learning project (a simple expense tracker) and lay it out by packages so the structure reflects the architecture. Important: we’re not building a “dream project with 200 files.” We’re building a small project, but with the right geography.

Let’s imagine this structure under src/main/kotlin:

src/main/kotlin
├── app
│   └── cli
│       ├── Main.kt
│       └── ParsedCommand.kt
├── domain
│   ├── model
│   │   └── Expense.kt
│   └── service
│       └── ExpenseService.kt
└── storage
    └── InMemoryExpenseStorage.kt

Note: Kotlin doesn’t force us to do it this way, but code-organization conventions strongly recommend it—especially that the directory structure should follow packages.

domain.model: domain model

Let’s start with the “cleanest” part—the model.

package domain.model

data class Expense(val title: String, val amount: Int)

No console, no commands, no “how to print nicely.” Just data.

domain.service: rules and operations

Now the service: it creates a correct Expense from raw input. Notice: the service does not store a list and does not print. It implements rules.

package domain.service

import domain.model.Expense

class ExpenseService {
    fun createExpense(title: String, amount: Int): Expense {
        val normalizedTitle = title.trim()
        require(normalizedTitle.isNotEmpty()) { "Title must not be empty" }
        require(amount > 0) { "Amount must be > 0" }
        return Expense(title = normalizedTitle, amount = amount)
    }
}

We import the model from domain.model; that’s a normal dependency “service → model.”

storage: in-memory storage

In-memory storage is our “minimal storage layer”: it can save an expense and return all expenses. It knows nothing about commands or the console; it only knows the model.

package storage

import domain.model.Expense

class InMemoryExpenseStorage {
    private val items = mutableListOf<Expense>()

    fun add(expense: Expense) {
        items.add(expense)
    }

    fun all(): List<Expense> = items
}

An important point: we expose List<Expense>, not MutableList<Expense>. This helps avoid turning the storage into a “public hallway” where anyone can mutate data however they want.

app.cli: commands and input parsing

The CLI layer is where we deal with strings, spaces, and human errors like “I typed add coffee twohundred.” Domain classes should not do that.

Let’s make a small ParsedCommand type so main doesn’t mess with “magic indices.”

package app.cli

data class ParsedCommand(val name: String, val args: List<String>)

And a parsing function (for now as simple as possible, with no claim of perfection):

package app.cli

fun parseCommandLine(line: String): ParsedCommand {
    val parts = line.trim().split(" ").filter { it.isNotEmpty() }
    val name = parts.firstOrNull()?.lowercase() ?: ""
    val args = if (parts.size > 1) parts.drop(1) else emptyList()
    return ParsedCommand(name = name, args = args)
}

Everything here is very “CLI-like”: trim, split, lowercase.

app.cli.Main: application wiring and scenario

And now main. It imports everything it needs and glues the scenario together: read a line → parse → apply rules → save → show the result.

package app.cli

import domain.service.ExpenseService
import storage.InMemoryExpenseStorage

fun main() {
    val service = ExpenseService()
    val storage = InMemoryExpenseStorage()

    print("Command: ")                  // Command:
    val cmd = parseCommandLine(readln())

    when (cmd.name) {
        "add" -> {
            val title = cmd.args.getOrNull(0) ?: ""
            val amount = cmd.args.getOrNull(1)?.toIntOrNull() ?: 0

            val expense = service.createExpense(title, amount)
            storage.add(expense)

            println("Added: $expense")  // Added: Expense(title=..., amount=...)
        }
        "list" -> println(storage.all())
        else -> println("Unknown command: ${cmd.name}")
    }
}

From a dependency perspective, everything is clean: CLI depends on domain and storage. Domain does not depend on CLI. Storage also does not depend on CLI. That means if tomorrow you want a different interface (for example, not console-based), you won’t have a “train of println calls.”

6. Imports as a problem indicator and the utils trap

There’s a useful technique: sometimes it’s enough to open a file and look at its import list to understand whether the architecture has “drifted.” If you see a file from domain.service importing something from app.cli, it’s almost always a signal: “we shoved a UI detail into domain logic.”

One more nuance: Kotlin name resolution rules consider imports by priority. For example, an explicit import usually has higher priority than a star import (*) or “found in the same package.” This doesn’t mean we should live in fear of imports. It means imports are part of the project design, not “garbage at the top.”

Very soon “convenience functions” appear in the project: formatMoney, readInt, normalizeTitle, parseSomething. And your hand reaches for creating a utils package and throwing everything in there. It looks like cleaning, but it often turns into a “box of wires”: you toss in anything you don’t yet know where to put.

The problem isn’t the name utils; it’s the lack of responsibility. When a utility isn’t tied to a layer, it starts pulling dependencies in every direction. For example, utils.formatExpense() suddenly starts importing domain.model.Expense, then someone adds println “for debugging,” and now the utility is no longer a utility—it’s a tiny portal of chaos.

It’s much calmer when helper functions live next to their layer. Command parsing—in app.cli, normalization rules—in domain.service, working with the stored list—in storage. A package is not a trash can; it’s an address.

7. Common mistakes

Mistake #1: domain code starts depending on CLI via an “innocent import.”
Usually it starts with the phrase “I just want to print an error message nicely.” And then import app.cli.printError appears. After that, domain can no longer be used independently of the console, and the responsibility boundary disappears. It’s better to let domain return a clear error (or throw via require), and let the CLI decide how to show it to the user.

Mistake #2: mismatch between folders and package because “Kotlin allows it.”
Yes, it does: a file can live anywhere. But source-organization recommendations explicitly say the directory structure should follow the package structure, especially on the JVM. Otherwise IDE navigation becomes odd, file moves become painful, and the project looks like a maze without a map.

Mistake #3: storage exposes MutableList, and any code can mutate the data.
From the outside it seems convenient: “I’ll be careful.” But a week later you’ll forget where exactly you were “careful,” and you’ll get unexpected state changes. Return List and keep mutation inside the storage layer—this makes it easier to control who changes data and where.

Mistake #4: star imports (import something.*) start living their own life.
A *-import can sometimes seem convenient, but in large projects it hurts readability and can lead to unexpected name conflicts. Plus, Kotlin name resolution has priorities: explicit imports “beat” what comes from *, which is yet another reason not to turn imports into a lottery.

Mistake #5: the utils package turns into a “dump for everything.”
While the project is small, it can feel like order. But once functions from different layers get mixed in, the package starts pulling dependencies in all directions and destroys responsibility boundaries. It’s better to keep “utilities” next to their layer and task—then imports are easier to manage, and the structure becomes self-explanatory.

1
Task
Kotlin SELF, level 39, lesson 1
Locked
User Registration
User Registration
1
Task
Kotlin SELF, level 39, lesson 1
Locked
Shopping List
Shopping List
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION