CodeGym /Courses /Kotlin SELF /Building a mini API without duplicates

Building a mini API without duplicates

Kotlin SELF
Level 14, Lesson 5
Available

1. The idea and principles of a mini input API

When you write your first console programs, it seems normal to copy 5–7 lines of input: “well, I just asked for the number again”. But half an hour later, you suddenly have ten places where you forgot trim(), three places where you accidentally used toInt() instead of toIntOrNull(), and one place where you print a prompt without a trailing space, so the user types the number right up against the text. And all of this is different bugs of the same nature: the logic is repeated, so it will drift.

A mini API is not a “big input framework”, but a small set of functions that you agree to use consistently. Our goal is to remove repeated pieces (printing the prompt, normalization, safe parsing, range checks) and leave in main() only what belongs to the program scenario: which data we ask for and what we do next.

Naming conventions

If you name functions randomly, a mini API quickly turns into a bag of spells: “does readNumber throw an exception or return null?”, “does getInt trim or not?”. So we introduce simple conventions and stick to them. It is like agreeing within a team that “Earl Grey tea” is not “latte coffee” (otherwise there will be tears, resentment, and unexpected null).

Let us agree on the following naming style:

Prefix / suffix Example Meaning (function promise)
read…
readIntOrNull(prompt)
The function reads from the console (
readln()
inside)
parse…
parseIntOrNull(raw)
The function does not read or print, it only parses a string
validate…
validateIntInRangeOrNull(x, min, max)
The function checks rules for an already prepared value
…OrNull
readNonEmptyLineOrNull(...)
May return
null
if “it failed to obtain a valid value”
without
OrNull
readLinePrompt(...)
Returns a value guaranteed (either a “raw string”, or a function that “cannot not return”)

A separate important note about require and check: they are not “about invalid user input”, they are about incorrect use of the function by the programmer. They throw exceptions and are used as precondition checks.

Composition without duplicates

To keep a mini API from turning into an “all-in-one machine for every possible case”, it helps to keep a simple level scheme in mind. Think of a pipeline: the input is the user raw string, the output is either a valid value or null, meaning “it failed at this step”.

Below is the diagram we will aim for (and which is easy to extend without copying code):

flowchart TD
    A["prompt + readln()"] --> B[normalization: trim/lowercase]
    B --> C[parse...OrNull: String -> T?]
    C --> D[validate...OrNull: T -> T?]
    D --> E[read...OrNull at the scenario level]

What matters here is that the “building blocks” are small and honest. parseIntOrNull() does not print “You did not enter a number”, because it has no idea how you want to talk to the user. It just says: “if I can parse it—here is an Int; if I cannot—here is null”. The scenario (usually main) decides what to do with null: exit, ask again (you already know loops), show a hint, or pick a default value.

2. Input utilities in InputUtils.kt

It is tempting to immediately write one function like readIntInRangeWithRetriesAndAngryMessages(...), but that is a direct path to a 60-line monster. We will go another way: assemble a file (or just a block in one .kt) where each function does one clear step. Then we will build more convenient “combined” utilities from those steps.

Reading a line with a prompt

Let us start with a safe and predictable “zero level”: print a prompt and read a line. Yes, it is trivial. That is exactly why it is worth extracting: trivial things in code are better centralized.


fun readLinePrompt(prompt: String): String {
    print(prompt)
    return readln()
}

Here we deliberately return String, not String?: in our console input scenarios we assume that the user does enter something. (End-of-input is a separate topic; for now, the general pattern is more important.)

Input normalization

Normalization is when we turn “  Yes  ” into a normal “yes”, and “  10  ” into a normal “10”. This is not “validation”, because we do not forbid anything; we just remove noise.

fun normalizeTrim(raw: String): String {
    return raw.trim()
}

fun normalizeCommand(raw: String): String {
    return raw.trim().lowercase()
}

If this feels too granular—great. Exactly these small details later save you dozens of lines, because you stop sprinkling trim() all over the code like confetti.

Pure parsing

Now let us write parsers. They do not read from the console and do not print. They can gracefully handle an empty string.

fun parseIntOrNull(raw: String): Int? {
    val s = normalizeTrim(raw)
    if (s.isEmpty()) return null
    return s.toIntOrNull()
}

fun parseDoubleOrNull(raw: String): Double? {
    val s = normalizeTrim(raw)
    if (s.isEmpty()) return null
    return s.toDoubleOrNull()
}

Yes, toIntOrNull() will return null for an empty string anyway, but the explicit check improves readability for a beginner: you can see that emptiness is a normal “failed to parse” outcome.

Now a “yes/no” parser. We want to distinguish between “no” and “I did not understand”. So we return Boolean?, not Boolean.

fun parseYesNoOrNull(raw: String): Boolean? {
    return when (normalizeCommand(raw)) {
        "yes", "y" -> true
        "no", "n" -> false
        else -> null
    }
}

Validation

Now validators. They take an already proper type (Int, Double, String) and check rules.

fun validateIntInRangeOrNull(x: Int, min: Int, max: Int): Int? {
    require(min <= max) { "Expected min <= max (min=$min, max=$max)" }
    if (x < min) return null
    if (x > max) return null
    return x
}

Here require(min <= max) is a precondition check: if the programmer passed incorrect bounds, continuing “as if everything is OK” is not acceptable. require exists exactly for this, and on failure it throws IllegalArgumentException.

For strings, let us make a validator “not empty after trim()”:

fun validateNonEmptyOrNull(raw: String): String? {
    val s = normalizeTrim(raw)
    if (s.isEmpty()) return null
    return s
}

And an example validation for a “strictly positive” number for Double (useful for prices, coefficients, etc.):

fun validatePositiveDoubleOrNull(x: Double): Double? {
    if (x <= 0.0) return null
    return x
}

Combined read…OrNull for the scenario

Now we can assemble functions that read from the console and use our building blocks inside. The main goal is to avoid duplicates inside, and to make identical things look identical.

fun readIntOrNull(prompt: String): Int? {
    val raw = readLinePrompt(prompt)
    return parseIntOrNull(raw)
}

fun readDoubleOrNull(prompt: String): Double? {
    val raw = readLinePrompt(prompt)
    return parseDoubleOrNull(raw)
}

Let us make a “non-empty line”:

fun readNonEmptyLineOrNull(prompt: String): String? {
    val raw = readLinePrompt(prompt)
    return validateNonEmptyOrNull(raw)
}

Let us make a “yes/no”:

fun readYesNoOrNull(prompt: String): Boolean? {
    val raw = readLinePrompt(prompt)
    return parseYesNoOrNull(raw)
}

And finally the most “tasty” utility: a number in a range. What matters is that there is no custom parsing here and no custom range logic—we reuse what we already wrote.

fun readIntInRangeOrNull(prompt: String, min: Int, max: Int): Int? {
    require(min <= max) { "Expected min <= max (min=$min, max=$max)" }

    val x = readIntOrNull(prompt) ?: return null
    return validateIntInRangeOrNull(x, min, max)
}

Notice the effect: if tomorrow you decide that readIntOrNull should, for example, handle trim() differently, you will change it in one place, and it will automatically improve all higher-level functions.

3. A readable main() as a scenario

Now we will do the most important exercise of this lecture: write main() so it looks like a script of communicating with the user. That is: first ask for the room name, then dimensions, then price, then output. No mess of trim() and toDoubleOrNull() at every step. If you have ever read someone else’s code and felt your brain trying to jump out the window—this is exactly what happens when you do not have these utilities.

Below is a small example app that calculates wall area (and optionally ceiling area) and estimates painting cost. We do not use collections, files, or “complex architecture”—only what is already available up to level 14.

fun main() {
    println("Room painting calculator v0")

    val roomName = readNonEmptyLineOrNull("Room name: ")
    if (roomName == null) {
        println("The name must not be empty.")
        return
    }

    val width = readIntInRangeOrNull("Width (1..50), m: ", 1, 50)
    if (width == null) {
        println("Width is invalid.")
        return
    }

    val length = readIntInRangeOrNull("Length (1..50), m: ", 1, 50)
    if (length == null) {
        println("Length is invalid.")
        return
    }

    val height = readIntInRangeOrNull("Height (2..10), m: ", 2, 10)
    if (height == null) {
        println("Height is invalid.")
        return
    }

    val priceRaw = readDoubleOrNull("Painting price per 1 m² (e.g. 12.5): ")
    val pricePerSqm = if (priceRaw == null) null else validatePositiveDoubleOrNull(priceRaw)
    if (pricePerSqm == null) {
        println("Price must be a number greater than 0.")
        return
    }

    val includeCeiling = readYesNoOrNull("Paint the ceiling? (yes/no): ")
    if (includeCeiling == null) {
        println("I did not understand the answer. Enter yes/no.")
        return
    }

    val wallsArea = 2.0 * (width + length) * height
    val ceilingArea = width.toDouble() * length.toDouble()
    val totalArea = if (includeCeiling) wallsArea + ceilingArea else wallsArea

    val totalCost = totalArea * pricePerSqm

    println()
    println("Room: $roomName")
    println("Wall area: ${"%.2f".format(wallsArea)} m²")
    println("Total area: ${"%.2f".format(totalArea)} m²")
    println("Cost: ${"%.2f".format(totalCost)}")
}

Yes, there is a repeating pattern here:

val x = read...
if (x == null) { println(...); return }

But the important difference is that this repetition is already at the “scenario level”. It describes a business decision: “if we could not obtain valid data, we end the program”. Low-level repetition (read a line, trim(), parse) is removed.

If later you want the behavior to be “do not exit, ask again”, you can change only the scenario without touching parsers and validators. (You already know loops, but today we deliberately do not implement “retry input” so as not to mix topics.)

4. How to keep the mini API small

It is very easy, once you get a taste for utilities, to start writing “more and more convenient” functions that eventually do everything at once: read, validate, print errors, retry, format prompts, and also get offended at the user for a wrong comma. It is fun for the first five minutes, and then you realize you do not have a mini API—you have a second main, just hidden inside a function.

A good balance usually looks like this: you have a few basic functions (readLinePrompt, parseIntOrNull, validateIntInRangeOrNull), and a few convenient “combined” functions that you actually need often (readIntInRangeOrNull, readNonEmptyLineOrNull, readYesNoOrNull). If you see that the next function ended up with six parameters and the phrase “just in case”, it is almost always a sign that you mixed responsibility levels.

It is also worth keeping in mind the difference between a “user error” and a “programmer error”. A user may type forty two instead of 42—that is expected, and then …OrNull returns null. But if a programmer calls readIntInRangeOrNull(prompt, 10, 1), that is a precondition violation, and it is better to catch it immediately with require(min <= max). require and check are designed for this kind of fail-fast behavior and throw exceptions so the problem is visible, rather than turning into a “quiet weird bug”.

5. Common mistakes when building a mini utilities API

Mistake #1: the function is named like it is non-nullable, but it returns null.
If you named a function readInt(...) but it returns Int?, you force the code reader to do archaeology: “where could null come from?”. The OrNull suffix is an honest signal: “handle null, it is part of the contract”.

Mistake #2: utilities print errors inside themselves, and then main() prints again.
At first it seems convenient: “let readIntOrNull print ‘You did not enter a number’”. But as soon as you have two scenarios (for example, in one place you want “not a number”, and in another “expected age”), the utility starts getting in the way. Usually it is better for the low level to return null, and for the scenario level to decide what and how to say to the user.

Mistake #3: mixing parsing and validation in one long function.
When one function does trim(), then toIntOrNull(), then range checks, then printing errors—it is hard to reuse and hard to “test in your head”. Splitting into parse…OrNull and validate…OrNull makes the code linear and lets you assemble different combinations without copy-paste.

Mistake #4: returning “magic values” instead of null.
Sometimes you want to return -1, 0, or Int.MIN_VALUE to “indicate an error”. This is almost always self-deception: -1 can be a real value (e.g., temperature), 0 can be valid (e.g., a discount), and you start adding extra conditions. null in Kotlin is much more honest for these cases: “value not obtained / did not pass validation”.

Mistake #5: missing precondition checks where they are truly needed.
If a function accepts min and max, and you do not verify that min <= max, then sometime in the future you will get weird behavior (for example, “the range accepts nothing”) and waste time debugging something you could have caught immediately. In such places require(...) is appropriate, because it is an error in using the function, not a user error.

Mistake #6: bloating signatures “just in case”.
A mini API stops being mini when you get functions like readIntInRangeOrNull(prompt, min, max, retries, defaultValue, errorMessage, allowEmpty, ...). As a rule, this means you mixed scenario logic (what to do on error) and utility logic (how to safely obtain a value). It is better to keep utilities simple and assemble complex behavior outside—in main() or in separate scenario functions.

Mistake #7: chaotic normalization in different places.
If one parser does trim(), another does not, and somewhere else you manually call lowercase() in main(), you will inevitably get “weird” bugs like “YES was not recognized, but yes was recognized”. Normalization must be consistent: it is better to have 1–2 small functions like normalizeTrim and normalizeCommand and use them the same way everywhere.

1
Task
Kotlin SELF, level 14, lesson 5
Locked
Terminal greeting
Terminal greeting
1
Task
Kotlin SELF, level 14, lesson 5
Locked
Age in the questionnaire
Age in the questionnaire
1
Task
Kotlin SELF, level 14, lesson 5
Locked
App rating
App rating
1
Task
Kotlin SELF, level 14, lesson 5
Locked
Sound command
Sound command
1
Survey/quiz
Input and validation functions, level 14, lesson 5
Unavailable
Input and validation functions
Input and validation functions
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION