CodeGym /課程 /Kotlin SELF /Interfaces as API boundaries

Interfaces as API boundaries

Kotlin SELF
等級 39, 課堂 2
開放

1. Interfaces as boundaries between layers

You can write an application without interfaces, and it will even work. Just like you can ride a bicycle with no hands — sometimes it works, until you hit a pothole. Interfaces are not for “beauty”; they exist to protect the code from change chaos: when you change storage or the report format, you do not want your command logic, service, printing, and half the project to start breaking because of one edit.

Let’s imagine we have an “expense tracking” project (a small tracker). At the domain level we want to be able to:

  • add an expense with validations,
  • get the list of expenses,
  • build a text report.

But how exactly expenses are stored (in a list, a map, a cache, a file — not today) and how exactly the report looks (plain text, a table, CSV — also not today) are details you will constantly want to change.

An interface in this story is a “power socket”: you do not have to know how a power plant works to charge your laptop.

Interface as a contract

It is very important not to turn an interface into a “god object” that can do everything. A good interface is a contract: minimum methods, maximum clarity. It answers: “What does the calling code need?” — and ignores: “What would be cool to add for the future?”.

There is a classic beginner trap: you wrote InMemoryExpenseRepository, then made the ExpenseRepository interface exactly as wide as your implementation, including all helper methods. As a result, the interface becomes not a contract but a “photo of the implementation”. Then it stops protecting the system: any new wish in the implementation drags interface changes with it, which means changes in all layers.

Keep this rule in mind:

An interface is not a list of your capabilities. An interface is a list of other people’s needs.

Domain model

Before writing repositories and exporters, we need a data model. The domain model should be as simple as possible: data and nothing extra.

// FILE: domain/model/Expense.kt
package domain.model

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

There is no println, no readln, no formatting, no storage. Only meaning: “an expense is a title and an amount”.

2. Repository: access contract for domain data

A repository (Repository) is the “entry point” for working with data. At our level (v1) it is just a contract: how to add an expense and how to get the list of expenses. Nothing fancy.

Important: a repository is not necessarily a database. Today it can be a simple in-memory list. The point is not where the data lives, but that domain code must not depend on a concrete storage mechanism.

Interface ExpenseRepository: narrow and boring means good

Let’s make the contract minimal: add() and all().

// FILE: domain/service/ExpenseRepository.kt
package domain.service

import domain.model.Expense

interface ExpenseRepository {
    fun add(expense: Expense)
    fun all(): List<Expense>
}

Why does all() return List instead of MutableList? Because we want to expose a “read-only view”, so external code cannot “accidentally” delete data directly.

In Kotlin there is an important practical idea: MutableList is a list with mutation operations, while List is “read-only”. Even if under the hood you have a mutable list, it is better to expose a read-only interface outward. This matches Kotlin’s general collections approach: there are read-only types and mutable types, and mutable ones have modification operations.

Implementation InMemoryExpenseRepository: hide MutableList inside

Now we implement in-memory storage. This is the storage layer, but it implements the domain contract.

// 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
}

Notice a detail: items is private. This is not a “minor thing”; it is direct protection against responsibility leaks. If items were public, the CLI could do repo.items.clear() and “break everything honestly, without warning”.

Nuance: a “read-only List” does not mean “object immutability”

There is a subtle Kotlin point here: if you return items as List, it restricts the caller at the type level (they cannot call add()), but it is still the same collection, just with a different “view”.

Sometimes this is fine (and for a v1 tutorial project — it is fine). But sometimes you want to return a “snapshot” (toList()), so external code cannot affect your state even indirectly.

It can be done like this:

override fun all(): List<Expense> = items.toList()

This is safer for encapsulation, but more expensive in memory/time. For v1 we will often keep the simple option, but it is important to understand that the choice exists.

3. Domain service

Now let’s gather the logic for “what counts as a valid expense” in one place. The service does not print, does not read input, and does not store data directly — it applies rules and talks to the 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()
}

It is important to see the architecture “geometry” of dependencies:

  • ExpenseService depends on the interface ExpenseRepository,
  • a concrete implementation (InMemoryExpenseRepository) will be provided from the outside, in the CLI,
  • the service does not know and must not know where and how data is stored.

This is dependency injection through the constructor (constructor injection) in the most basic, “manual” form.

4. Exporter: a separate contract for report formatting

Now the second boundary — reports. Beginners often do this: the service builds a string and then also prints it. Or the CLI builds a report manually. Both variants create unnecessary coupling.

Formatting logic is a separate responsibility: “turn data into text”. We explicitly design it so that an exporter returns a String instead of calling println. Why? Because printing is the CLI layer, while formatting is a separate role that can be reused.

Interface ReportExporter

// FILE: domain/service/ReportExporter.kt
package domain.service

import domain.model.Expense

interface ReportExporter {
    fun export(expenses: List<Expense>): String
}

Again, the interface is narrow: one method, one job. It does not know about the console, does not know about commands, does not know about the repository. You give it data — it returns text.

Implementation PlainTextExporter: a simple plain-text report

// 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}"
        }
    }
}

This exporter uses the most straightforward format possible. And that is good: when you design architecture, it is better to start with a simple format to see the boundaries.

One more implementation: a “table” with alignment

Sometimes you want the report to look cleaner. We can make a second exporter without changing the service and without changing the 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"
        }
    }
}

Key effect: you can switch the report format by replacing a single implementation in the CLI (we will do that below), without rewriting the rest of the system.

5. How it is wired: the CLI assembles dependencies

The most common mistake at this stage is to “drag everything back into main”. So we keep main short: it creates a repository, service, exporter, and calls operations.

// 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
}

Notice: the CLI did println, because that is its job. The exporter returned a string. The service applied rules. The repository saved. Everyone has their own role, and nobody steps into someone else’s territory.

6. Why a “narrow API” is not pedantry but protection from future problems

Right now it is tempting to add everything into ExpenseRepository: remove, update, findByTitle, clear, count, totalAmount, and “this other thing, it might be useful”. But that turns the interface into the “center of the universe”, and every layer starts depending on too many details.

Instead, keep interfaces minimal, and express complex operations either as separate service methods (domain rules) or as reports (exporters).

Below is a small table to reinforce the intuition.

Question Bad answer Good answer
“Where should println go?” “Into the exporter, it is about reports” “Into the CLI: the exporter returns String”
“Who should trim the title?” “The CLI, because input is there” “The Service: it is a domain rule”
“Can we return MutableList outward?” “Yes, it is faster” “No, outward is List; mutation is hidden”
“Should all() do toList()?” “Always yes, because it is nicer” “Sometimes yes: it is a snapshot, but it has a cost”

7. Dependency diagram: who is allowed to know about whom

To avoid your head turning into a Kotlin compiler (even if that sounds like a dream for some people), it helps to keep this picture:

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

The idea: the CLI can assemble the system from parts and run use cases. The domain holds rules and contracts. Storage implements the contract. The exporter implements the contract. But the domain must not “import the CLI”, otherwise layers get mixed up.

8. Common mistakes

Mistake 1: an interface “just in case” becomes huge.
Usually it looks like this: you wrote InMemoryExpenseRepository, saw that you could “if you wanted” delete, clear, sort, and sum — and you added all of that into ExpenseRepository. Then the CLI starts using half of the methods, the service uses the other half, and you can no longer change the repository implementation without rewriting the whole project. The fix is boring but effective: leave in the interface only the methods without which the caller code truly cannot live.

Mistake 2: the repository “leaks outward” via MutableList.
When all() returns MutableList, external code gains the right to change the repository’s internal state directly. That breaks service invariants: it may enforce amount > 0, and then someone in the CLI adds an expense with -100 directly into the list. So we expose List outward and keep MutableList inside. In Kotlin this matches the overall model of read-only and mutable collections.

Mistake 3: the exporter prints by itself (println inside export).
If the exporter prints, it becomes “half CLI”, and it is also impossible to reuse properly: you cannot get the report string and, for example, show it as part of another message. Keep the rule: the exporter returns String, and printing is in the CLI.

Mistake 4: the service creates the repository inside itself (val repo = InMemoryExpenseRepository()).
This makes the service tightly coupled to a specific storage implementation. It seems small, but it instantly kills the whole point of an interface. The service should depend on the contract (ExpenseRepository) and receive an implementation via the constructor. Then the CLI can “swap in” another implementation without changing domain code.

Mistake 5: all(): List<Expense> = items is perceived as “full protection from changes”.
A read-only List does restrict access to mutation operations, but it still can be a “view” of the same collection. Sometimes that is enough; sometimes you want to return a copy (toList()), i.e., a snapshot of the data. Kotlin emphasizes the difference between copying a collection and creating a second reference to the same collection.

1
任務
Kotlin SELF, 等級 39, 課堂 2
上鎖
數字儲存庫
數字儲存庫
1
任務
Kotlin SELF, 等級 39, 課堂 2
上鎖
匯出字串
匯出字串
1
任務
Kotlin SELF, 等級 39, 課堂 2
上鎖
商品目錄服務
商品目錄服務
1
任務
Kotlin SELF, 等級 39, 課堂 2
上鎖
兩種報表
兩種報表
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION