CodeGym /Courses /Kotlin SELF /Decomposing into functions: input, comparison, messages, ...

Decomposing into functions: input, comparison, messages, and contracts

Kotlin SELF
Level 15, Lesson 2
Available

1. Why a “long sheet” inside main() gets in the way

If you’re just starting to program, it’s very easy to write the entire game code right inside main(): read a string, parse it, compare it, print a hint, increment a counter — and repeat. At first it feels fast. But after 30–40 lines you’ll notice you’re afraid to touch the code, because any change breaks something “somewhere else”. Functions are like storage boxes: put things in their places, and your brain stops overheating.

Imagine the game is a kitchen. main() is the table where you cook. If everything is on the table at once (flour, eggs, knives, pots, a microwave manual, and also somehow a keyboard), cooking turns into a quest. Functions let you put “repeated ingredients” and “small operations” into separate containers.

In our game, it’s especially convenient to move these into functions:

  • input and validation of the guess (user mistakes almost always happen there);
  • comparing the guess with the secret (this is pure logic; it’s convenient to isolate);
  • building messages (“too low/too high/correct”), so strings don’t get smeared across the project.

A small diagram of where we’re heading:

flowchart TD
    A["main(): game scenario"] --> B["readGuessOrNull(): input + validation"]
    A --> C["compareGuess(): comparison"]
    A --> D["hintText(): hint text"]

2. Function contract

Before writing functions, it’s important to learn to formulate their contract. A contract is a simple agreement: “what the function expects as input”, “what it returns”, “what a special result means (for example null)”, and “whether it has side effects (does it print anything, does it read input)”.

If you don’t pin down the contract, a classic situation starts: you write readGuess(), and two hours later you ask yourself: “Does it print the prompt? Does it validate the range? And if the user entered abc — does it crash or return 0?” And now you’re debugging not the game, but your own guesses about your own code.

It helps to keep contracts in your head as a small table:

Function Input Output Side effects What “error” means
readGuessOrNull(min, max)
input range
Int?
reads
readln()
, prints a prompt
null
= “failed to obtain a valid number”
compareGuess(guess, secret)
two numbers
Int (-1/0/1)
none not expected (input is valid)
hintText(compareResult)
-1/0/1
String
none an “unknown code” can be treated as
else

Notice: we intentionally separate the “dirty” world (user input, errors, spaces, letters) and the “clean” one (comparing two Ints). This makes life much easier.

3. Reading a guess: readGuessOrNull(min, max)

User input is where the game breaks most often. The user might enter 42, or " 42 ", or "forty two" (and be sure they were helpful). So our input function must be resilient: it must not crash if the input isn’t a number, and it must be able to filter values outside the range.

The main contract idea here is: we return Int?. If everything is fine — return a number. If not — return null. It’s honest and clean: the type Int? makes it obvious the result might be missing, and the compiler forces us to handle that case.

Basic implementation with trim() and toIntOrNull()

Let’s start with a very straightforward version. It’s not perfect, but it’s already useful and understandable.

fun readGuessOrNull(min: Int, max: Int): Int? {
    print("Enter a number from $min to $max: ")
    val raw = readln().trim()

    val guess = raw.toIntOrNull() ?: return null
    if (guess !in min..max) return null

    return guess
}

There are a few important details here.

First, trim() removes spaces at the edges — so the string " 42 " becomes "42". Second, toIntOrNull() tries to parse an Int, but instead of crashing it returns null if the string isn’t a number. Third, we check the range: guess !in min..max. Finally, early return null prevents the function from growing nested ifs.

The pattern “read a string → prepare → parse” shows up in Kotlin all the time, especially in console tasks, and is often wrapped in small helper functions for reading typed values.

Should the function print an error message

Now a small architectural dilemma (without big words). There are two approaches.

If readGuessOrNull() prints “Input error” itself, then main() gets shorter, but the function becomes responsible for two things: input and messages. If the function simply returns null, and main() prints the message, then the function is “cleaner”, and the messaging scenario is controlled in one place.

For a learning project, it’s most often convenient to keep the function neutral: let it return null, and let the caller print the message. Then the game can easily change its messaging style without touching parsing.

If you still want to hint to the user immediately, you can make a version that prints text, but it’s better to make the contract explicit (at least in the name or a comment).

fun readGuessOrNullWithMessage(min: Int, max: Int): Int? {
    val guess = readGuessOrNull(min, max) ?: run {
        println("Invalid input") // message here, but then the function is “chatty”
        return null
    }
    return guess
}

Note: here run { } is used as a block for a neat early exit. If you’re not confident with run yet, you can skip this option and keep everything in main().

4. Comparing numbers: compareGuess(guess, secret)

Once input has turned into a valid number, the nicest part begins: regular logic. Here we compare the guess with the secret and want one of three outcomes: “less”, “greater”, “equal”.

Important: this function must not read input and must not print messages. It should do exactly one thing: compare two Ints. Then it’s easy to verify separately (in your head or with small calls).

Let’s agree on the result format:

  • -1 if the guess is less than the secret;
  • 0 if the guess is correct;
  • 1 if the guess is greater than the secret.
fun compareGuess(guess: Int, secret: Int): Int {
    return when {
        guess < secret -> -1
        guess > secret -> 1
        else -> 0
    }
}

Why not Boolean? Because Boolean gives only two states, and we need three. Why not a string? Because a string is already a “representation for a human”, not logic. We’ll produce the string in the next function.

A small self-check (just to feel that the function behaves as expected):

fun main() {
    println(compareGuess(10, 20))  // -1
    println(compareGuess(30, 20))  // 1
    println(compareGuess(20, 20))  // 0
}

5. Hint text: hintText(compareResult)

Messages are what makes the game feel “alive”. But if texts are scattered across the code, it’s hard later to change the style, fix a typo, or add a “mood exclamation mark”. So it’s logical to keep hint texts in one place.

We already chose a comparison result code (-1/0/1), so we can make a function that turns this code into a human-readable phrase.

fun hintText(compareResult: Int): String {
    return when (compareResult) {
        -1 -> "Too low"
        1 -> "Too high"
        else -> "Correct!"
    }
}

Notice the else. We could write 0 -> "Correct!", but else here plays the role of a “safety net”: if someone accidentally returns, for example, 2, we still get some message rather than emptiness. In production this is debatable, but in learning code it can even be more useful, because the game won’t “fall into silence”.

Quick mini-test:

fun main() {
    println(hintText(-1)) // Too low
    println(hintText(1))  // Too high
    println(hintText(0))  // Correct!
}

6. One-attempt scenario and mini-tests

We’ll assemble a full attempt loop in the next lecture, but even now it’s useful to see how functions turn main() into a readable scenario, and how to test them “in parts”.

Gluing everything into “one attempt”

Imagine we make just one attempt (so we don’t get into while too early) — just a composition demo.

fun main() {
    val min = 1
    val max = 100
    val secret = 42 // temporarily fixed for the example

    val guess = readGuessOrNull(min, max)
    if (guess == null) {
        println("Invalid input")
        return
    }

    val result = compareGuess(guess, secret)
    println(hintText(result))
}

What’s nice here: the code reads “like text”.

First we set the range and the secret. Then we get a guess. If there is no guess, we honestly terminate. If there is, we compare and print a hint. In this fragment there isn’t a single detail about toIntOrNull(), trim(), etc. Those details are “hidden” in a separate function, and main() doesn’t have to remember how exactly we clean the string there.

Helper functions for scenario readability

As a project grows, even small pieces like an “attempt header” or an “end of game message” start to repeat. Today we’re not writing the final game logic end-to-end yet, but we can prepare a few “text” functions that will make the next step easier.

For example, a function for the string “Attempt X of Y”:

fun attemptHeader(attempt: Int, maxAttempts: Int): String {
    return "Attempt $attempt of $maxAttempts"
}

Or a function for the final win message (without loop details for now):

fun winText(attempt: Int): String {
    return "Win in $attempt attempts!"
}

Why is this useful? Because a string is also part of the logic. It affects how the user understands the rules of the game. If you keep it as a separate function, you’re less likely to accidentally produce “Attempt 0 of 7” in one place and “Attempt 1 of 7” in another.

How to manually test functions before assembling the game

While we don’t have a full loop, it can feel like testing the game is impossible. In fact it’s possible — and it’s a very useful habit: test functions with small calls. It’s almost like “playing the game in parts” without assembling the whole box.

The most common trick is to temporarily fix the secret so the behavior is reproducible (randomness gets in the way of debugging).

fun main() {
    val secret = 50

    val result1 = compareGuess(10, secret)
    println(hintText(result1)) // Too low

    val result2 = compareGuess(90, secret)
    println(hintText(result2)) // Too high

    val result3 = compareGuess(50, secret)
    println(hintText(result3)) // Correct!
}

This way you can verify that the comparison and the hint texts “match in meaning”. If you accidentally swap the branches for guess < secret and guess > secret, it will show up immediately: you’ll get “Too high” where it should be “Too low”. And you’ll catch the bug before you add the loop and attempt counter.

7. Typical mistakes when decomposing input and logic

Mistake #1: the input function returns a “magic number” instead of null.
A very common variant: readGuess() returns 0 on error. Then it suddenly turns out that 0 can be a valid number (or will become valid if you change the range to 0..100). As a result, an input error turns into “normal input” and quietly and unpleasantly breaks the game logic. Int? solves this at the type level: an error cannot be confused with a number.

Mistake #2: mixing input, comparison, and printing in one function “because it’s shorter”.
At first it seems that makeAttempt() is ideal: it reads a number, compares it, prints “Too high”, and also increments the attempt. But as soon as you need to change the policy “does invalid input consume an attempt”, you’ll start cutting that function into pieces in panic mode. It’s better to separate from the start: input separately, comparison separately, text separately.

Mistake #3: using toInt() instead of toIntOrNull() for user input.
toInt() is good when you’re confident in the data (for example, inside your own code). But user input is unreliable by definition, and toInt() will throw an exception and terminate the program. toIntOrNull() gives exactly what you need for a game: “did we get a number or not”.

Mistake #4: validating the range after comparing with the secret.
Sometimes people do: “I’ll compare with the secret first, and then I’ll check whether the number is in range.” Then the user can enter 1000000, and you honestly say “Too high”, even though by the game rules such a number shouldn’t participate at all. The range is part of the input contract, so the check must happen before the comparison.

Mistake #5: message texts are scattered across the code and start to differ.
Today you wrote “Too high”, tomorrow elsewhere “Way too high!”, the day after “High”. As a result, the user feels like the game was written by three different people (and one of them is you on Monday morning). The hintText() function and small text helpers help keep the style consistent.

1
Task
Kotlin SELF, level 15, lesson 2
Locked
Comparison code
Comparison code
1
Task
Kotlin SELF, level 15, lesson 2
Locked
Decoding the code
Decoding the code
1
Task
Kotlin SELF, level 15, lesson 2
Locked
Number by the rules
Number by the rules
1
Task
Kotlin SELF, level 15, lesson 2
Locked
Single check
Single check
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION