CodeGym /행동 /Kotlin SELF /Client and scenarios architecture: no “network in CLI”

Client and scenarios architecture: no “network in CLI”

Kotlin SELF
레벨 58, 레슨 4
사용 가능

1. Why “network in CLI” becomes a problem

When you write your first network program, you really want to do everything directly in main: read a command, immediately do client.get(...), immediately parse JSON, immediately println. In a small example this even looks “fine”, like instant noodles: pour boiling water — and it’s ready. The problem is that after a couple of new commands, such noodles start living their own life and taking revenge for the shortcuts.

Imagine we already have a console application from previous days — a hypothetical expense tracker. Let it store expenses locally, and today we want to add a tip command that fetches the “financial tip of the day” from a remote server. Sounds harmless — right up to the moment you try to do it “directly in the CLI”.

Putting network code in the CLI usually leads to three problems at once.

First, responsibilities get mixed: in one place you have command parsing, HTTP headers, JSON models, and error handling. Second, it’s unclear what to test: the “command” or the “network”? Third, any change (for example, a different URL or a new response format) forces you to dig into the “sacred main”, which is already scary to touch because, like an ancient artifact, it’s held together by sheer luck.

To get out of this, we’ll split the program into two new layers:

  1. Client layer — “how we go to the network”.
  2. Scenario layer — “why we go to the network and what we do with the result”.

And the CLI will remain what it should be: “read command → call scenario → print result”.

2. Layer diagram: who is responsible for what

When people say “architecture”, beginners often hear “now there will be 43 folders, 12 abbreviations, and one shamanic tambourine”. We won’t do that. We need the simplest, educational scheme that actually helps: the CLI doesn’t know about Ktor or HTTP details, the scenario doesn’t print to the console, and the client doesn’t decide what to say to the user.

Here is the visual model (as a block diagram) that we’ll keep returning to:

flowchart TD
    CLI["CLI (main): 읽은 명령을 처리하고 텍스트를 출력"]
    SC["Scenario: 결과로 무엇을 할지 결정"]
    API["Client API: 원격 서비스 인터페이스"]
    KTOR["Ktor implementation: HttpClient + 요청"]
    NET["Internet/Server"]

    CLI --> SC --> API --> KTOR --> NET
    KTOR --> API --> SC --> CLI

The idea is simple: the lower the layer, the less it “knows” about your program and the more it “knows” about the technology. So the client knows HTTP and JSON, but doesn’t know that you have a tip command. The scenario knows what a “tip of the day” is, but doesn’t know what headers the request has. The CLI knows that the user typed tip, but doesn’t know what HttpResponse is.

It’s useful to keep a small table in mind:

Layer What it does What it does NOT do
CLI reads commands, prints messages does not build HTTP requests, does not parse JSON
Scenario decides “what to return to the user” does not print, does not manage HttpClient
Network Client goes to the network, returns data/errors does not know about commands and UI texts

This layout pairs well with Kotlin code and familiar code-organization rules: keep related things close, don’t sort methods alphabetically, but go “top to bottom by meaning” — this matches general recommendations about formatting conventions.

3. Network-layer contract: interface and explicit result

The first practical step is to agree on what exactly the network layer returns. This is a key point: if the client returns a “bare HttpResponse”, you drag HTTP details upward. If the client does println, you lose control of the output. So the most beginner-friendly option is to return an explicit result, where success and errors are separated by types.

Explicit request result: ApiResult

Let’s start with a simple sealed class that can distinguish three cases:

  1. success (data received),
  2. HTTP error (there is a response, but it’s non-2xx),
  3. network error (exception, timeout, unavailability, etc.).
sealed class ApiResult<out T> {
    data class Ok<T>(val value: T) : ApiResult<T>()
    data class HttpError(val status: Int, val body: String) : ApiResult<Nothing>()
    data class NetworkError(val message: String) : ApiResult<Nothing>()
}

Response model and remote-service interface

Now let’s define a response model for our tip command. Let the server return JSON like:

{ "text": "월급을 받은 직후 수입의 10%를 먼저 저축하세요" }

Then the Kotlin model:

import kotlinx.serialization.Serializable

@Serializable
data class TipResponse(val text: String)

And here is the main element of the architecture — the interface describing the capabilities of the remote service:

interface TipsApi {
    suspend fun fetchDailyTip(): ApiResult<TipResponse>
}

Notice two things.

First, it’s suspend — our network is asynchronous, and we are already used to that from coroutines.

Second, the CLI is no longer required to know what Ktor or HttpResponse is, or how headers work. The CLI only knows: “there is TipsApi, and it can be asked for the tip of the day”.

This approach matches the idea of a “narrow contract”: you describe what the program needs, not how you will obtain it (Ktor today, another client tomorrow). Ktor fits perfectly into such a model: it can be an implementation, not the meaning of the program.

4. Ktor client implementation: technical details live here

Now we’ll implement TipsApi using Ktor. This is exactly where all the “technical stuff” belongs: HttpClient, URL, status checks, body reading, JSON deserialization, and exception handling.

HttpClient factory

First, a client factory (so we create it in one place and configure it consistently):

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json

fun buildHttpClient(): HttpClient =
    HttpClient(CIO) {
        install(HttpTimeout) { requestTimeoutMillis = 3_000 }
        install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) }
    }

TipsApi implementation via Ktor

Now the API implementation. We’ll intentionally stick to the style “explicitly got HttpResponse → explicitly read the body”, so the code stays readable:

import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsText

class KtorTipsApi(
    private val client: HttpClient,
    private val baseUrl: String
) : TipsApi {
    override suspend fun fetchDailyTip(): ApiResult<TipResponse> {
        return try {
            val response: HttpResponse = client.get("$baseUrl/tip")
            if (response.status.value in 200..299) ApiResult.Ok(response.body())
            else ApiResult.HttpError(response.status.value, response.bodyAsText())
        } catch (e: Exception) {
            ApiResult.NetworkError(e.message ?: "Network error")
        }
    }
}

This is where it’s important to feel the responsibility boundary. This class:

  • builds the URL,
  • makes the request,
  • checks the status,
  • returns a clear ApiResult.

But it does not print and does not decide what to tell the user. It just honestly returns the result.

5. Scenarios and CLI: each does its own job

If the client returns ApiResult, we need a place where that result turns into a “clear human response”. That’s the scenario. It lives “above” the network, but “below” the CLI.

Scenario: converting ApiResult into meaning

A scenario is great because it’s convenient to keep rules like: “if HTTP 404 — say one thing, if timeout — another, if success — show the tip text”.

Let’s make a scenario that returns a ready string for the CLI:

class GetDailyTipScenario(private val api: TipsApi) {
    suspend fun execute(): String {
        return when (val r = api.fetchDailyTip()) {
            is ApiResult.Ok -> "오늘의 팁: ${r.value.text}"
            is ApiResult.HttpError -> "팁 서비스가 HTTP ${r.status}를 반환했습니다"
            is ApiResult.NetworkError -> "팁을 가져오지 못했습니다: ${r.message}"
        }
    }
}

This code looks “too simple”, and that’s the point. The scenario is where the program becomes a program, not a set of protocols.

Notice another architectural detail: the scenario depends on the interface TipsApi, not on KtorTipsApi. This allows us to swap the implementation (for example, with a “stub” for development) without changing the scenario and CLI.

CLI: command → scenario → output

Now the nicest part: main() does not have to understand HTTP, JSON, or status codes. It simply manages input/output and the resource lifecycle.

Let’s make a mini-CLI with commands tip and exit. For simplicity, we’ll keep the command-reading loop as you have done many times before:

import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val client = buildHttpClient()
    try {
        val api: TipsApi = KtorTipsApi(client, baseUrl = "https://example.com")
        val scenario = GetDailyTipScenario(api)

        while (true) {
            print("> ")
            when (readln().trim()) {
                "tip" -> println(scenario.execute())
                "exit" -> return@runBlocking
                else -> println("명령: tip, exit") // Commands: tip, exit
            }
        }
    } finally {
        client.close()
    }
}

Notice: main() now reads like an instruction, not like an article titled “how the internet works”.

And yes, try/finally around client.close() is not paranoia — it’s an adult habit. Networks love resources, and resources love being closed.

6. Dependency composition: assemble the app in one place

As an application grows, there’s a temptation to “create everything wherever”: HttpClient inside the API, API inside the scenario, scenario inside the command handler… and suddenly you have 17 clients and 17 timeouts because “it creates itself”.

To avoid that, we use one simple trick: compose dependencies in one place (sometimes called a “composition root”). In a learning project, this can be a separate function or a small class.

For example, let’s make an AppContext that creates and holds everything needed:

import io.ktor.client.HttpClient

class AppContext(baseUrl: String) : AutoCloseable {
    private val client: HttpClient = buildHttpClient()

    val tipsApi: TipsApi = KtorTipsApi(client, baseUrl)
    val getDailyTipScenario = GetDailyTipScenario(tipsApi)

    override fun close() = client.close()
}

And then main() becomes even cleaner:

import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    AppContext(baseUrl = "https://example.com").use { ctx ->
        println(ctx.getDailyTipScenario.execute())
        // Today's tip: ...
    }
}

Here we use the same principle you already saw in I/O topics: a resource is created in one place and closed there. HttpClient has close(), and use conveniently wraps the lifecycle.

7. Extend without pain: a new endpoint and minimal changes

Architecture is considered successful not when “everything looks pretty in folders”, but when a new feature is added locally. Let’s test that.

Imagine that tomorrow you want a ping command to quickly check whether the service is alive (or just to practice). In a bad architecture, you dig into main() and start adding requests there. In ours, you add a method to the API, an implementation in the Ktor client, and a scenario. You touch the CLI minimally.

Update the contract

Let’s add to the contract:

interface TipsApi {
    suspend fun fetchDailyTip(): ApiResult<TipResponse>
    suspend fun ping(): ApiResult<String>
}

Add implementation to the Ktor client

Implementation (briefly, as text):

import io.ktor.client.request.get
import io.ktor.client.statement.bodyAsText

override suspend fun ping(): ApiResult<String> {
    return try {
        val response = client.get("$baseUrl/ping")
        if (response.status.value in 200..299) ApiResult.Ok(response.bodyAsText())
        else ApiResult.HttpError(response.status.value, response.bodyAsText())
    } catch (e: Exception) {
        ApiResult.NetworkError(e.message ?: "Network error")
    }
}

Add a scenario

Scenario:

class PingScenario(private val api: TipsApi) {
    suspend fun execute(): String =
        when (val r = api.ping()) {
            is ApiResult.Ok -> "ping: ${r.value}"
            is ApiResult.HttpError -> "ping: HTTP ${r.status}"
            is ApiResult.NetworkError -> "ping: ${r.message}"
        }
}

And only at the very end — you add one branch in the CLI. This is the main sign that the layers work: changes “don’t spread”.

8. Common mistakes

Mistake #1: creating HttpClient inside each request function.
People often do this “to make it simpler”: create HttpClient inside fetchDailyTip(), do get, and close it. In practice, you get extra overhead, it’s harder to control timeouts/plugins, and at some point you start forgetting to close the client in one of the branches. It’s better to create the client once (in main or AppContext) and pass it into the API implementation.

Mistake #2: returning HttpResponse outward “let them deal with it”.
This looks like saving effort, but in reality you push HTTP details upward, and then status/bodyAsText() pops up in scenarios and the CLI. That is exactly what we were trying to avoid. It’s better to return ApiResult<T> or another explicit result, so upper layers work with meaningful types rather than transport details.

Mistake #3: doing println inside the network client.
It’s very tempting to “help yourself with debugging”: print URL, status, body. But then those prints end up in user output and interfere. If you need logging — that’s a separate topic and a separate responsibility. At the current level, keep the rule: the client returns data/errors, and only the CLI prints.

Mistake #4: trying to parse body<T>() for any status code.
If the server returns 400/500, the body may be a completely different JSON than you expect (or not JSON at all). Then you’ll get an exception during deserialization and lose the meaning of the error. Keep discipline: first check the status, and only in the success branch read body<T>(), and in the error branch read bodyAsText().

Mistake #5: “catch everything” and turn it into one text like “something went wrong”.
When you do catch (Exception) and return the same phrase every time, you deprive yourself (and the user) of understanding: did the internet go down, was it a timeout, was the URL wrong, or did the server honestly say “your data is invalid”. Even if you’re not doing fine-grained classification yet, at least separate HTTP errors from network exceptions — it dramatically improves predictability.

Mistake #6: mixing scenario and CLI: the scenario starts reading readln() or printing.
Sometimes it feels convenient: “the scenario knows what to ask the user”. But then the scenario stops being a scenario layer and turns into a second main(). Keep the boundary: input/output lives in the CLI, the scenario lives in the logic, the client lives in the network. It’s boring, but boring means reliable (in a good way).

1
과제
Kotlin SELF, 레벨 58, 레슨 4
잠금
호출 결과
호출 결과
1
과제
Kotlin SELF, 레벨 58, 레슨 4
잠금
가짜 서비스
가짜 서비스
1
과제
Kotlin SELF, 레벨 58, 레슨 4
잠금
팁 시나리오
팁 시나리오
1
과제
Kotlin SELF, 레벨 58, 레슨 4
잠금
Ktor 클라이언트
Ktor 클라이언트
1
설문조사/퀴즈
Network, 레벨 58, 레슨 4
사용 불가능
Network
Network
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION