CodeGym /Courses /Kotlin SELF /Preconditions and state checks: require and check

Preconditions and state checks: require and check

Kotlin SELF
Level 31, Lesson 4
Available

1. Fail-fast and the difference between require and check

Why “fail earlier” at all: the fail-fast idea

If you’re just getting started, it may seem like a good program should be polite and patient: “well, the user entered nonsense — let’s quietly substitute 0, an empty string, and somehow continue.” In practice, that kind of “kindness” often turns into accumulating errors: the program keeps running, but the data becomes garbage, and eventually everything breaks… only much later and in a much less understandable way.

The fail-fast approach (literally “fail quickly”) says: if the logic no longer makes sense, it’s better to stop immediately and explain what exactly was wrong. Kotlin directly supports this style with standard precondition functions: they automatically throw exceptions with a clear type.

To make the picture come together, here’s a small diagram (it’s about meaning, not syntax):

flowchart TD
    A[Got data] --> B{Is the data valid?}
    B -- No --> C[Fail-fast: require/check -> exception]
    B -- Yes --> D[Continue the logic]
    D --> E{Is the state correct?}
    E -- No --> F[Fail-fast: check -> exception]
    E -- Yes --> G[Predictable result]

The biggest fail-fast benefit in a learning project: you stop guessing “why it calculates weirdly” and start getting answers like “Age must be >= 0, got -5.” It’s surprising how much that reduces the urge to throw a laptop out the window (I tested it; the window did nothing wrong).

require vs check: similar on the surface, different in meaning

From the outside, require(condition) and check(condition) look almost identical: you pass a condition and (usually) a message. But their meaning is different — and that matters, because meaning turns into an exception type, and an exception type is a hint for you and for whoever will read your code after you.

require() is used to validate input arguments, while check() is used to validate the correctness of an object’s (or a variable’s) state. When require() fails, it throws IllegalArgumentException; when check() fails, it throws IllegalStateException.

Let’s summarize it in a table (this is genuinely worth keeping in mind):

The question you’re asking What to use Typical thought Exception
“I was given bad data; I can’t continue”
require(...)
“The argument is invalid”
IllegalArgumentException
“The data is fine, but the object is currently in an impossible/forbidden state”
check(...)
“The state is invalid”
IllegalStateException

A very rough, but memorable analogy: require is the bouncer at the club entrance (“no sneakers”), and check is security inside (“no toaster in the pool”). If it feels like “both are forbidding something,” you’re right. But the reasons for “not allowed” are different.

2. require: protecting inputs

When you create an object, you want it to be correct right away. This is a key beginner-level OOP idea: if an object exists, you can trust it. In Kotlin, a typical way to achieve this is to put checks in init { ... } or directly in the constructor logic.

Minimal example of require in init

Let’s start with something as simple as possible to build the habit:

class Age(val value: Int) {
    init {
        require(value >= 0) { "Age must be >= 0, got $value" }
    }
}

fun main() {
    println(Age(10).value) // 10
}

Here we’ve locked in the rule: age cannot be negative. Notice that we’re not trying to “fix” it; we’re forbidding the creation of an invalid object. And that’s normal: if you got -10, that’s not “almost an age,” it’s an input error.

Example from a learning project: an expense tracker

Let’s continue with a practical example: a console expense tracker. Previously, we could store an expense as a set of fields, but now we want the Expense object to be unable to exist in a garbage state.

Let’s make a small class:

class Expense(
    val amountCents: Int,
    val category: String,
    val note: String
) {
    init {
        require(amountCents > 0) { "amountCents must be > 0, got $amountCents" }
        require(category.isNotBlank()) { "category must not be blank" }
        require(note.length <= 100) { "note must be <= 100 chars, got ${note.length}" }
    }
}

Pay attention to the style: the message should explain what was expected and what was received. This isn’t aesthetics — it’s debugging speed.

Now creation:

fun main() {
    val e = Expense(amountCents = 1999, category = "Food", note = "Pizza")
    println("${e.category}: ${e.amountCents} cents") // Food: 1999 cents
}

If someone tries to create Expense(amountCents = 0, ...), the object won’t be created — and that’s correct: a zero expense most often means we failed to parse a number somewhere or mixed up the currency.

require also works for regular methods

Preconditions are needed not only when creating an object. If you have a method that takes arguments from the outside, you can protect the input with require as well: that’s exactly about arguments without which the function cannot work.

Imagine we have a helper method for formatting an amount:

fun formatCents(amountCents: Int): String {
    require(amountCents >= 0) { "amountCents must be >= 0, got $amountCents" }
    val dollars = amountCents / 100
    val cents = amountCents % 100
    return "$dollars.${cents.toString().padStart(2, '0')}"
}

fun main() {
    println(formatCents(1999)) // 19.99
}

Yes, we could “silently” turn -5 into 0. But then you’d lose the signal that you have a bug somewhere.

3. check: protecting an object’s state

Now let’s move on to check. You need it when the input data is fine, but the object itself should not perform the operation right now. This often happens with objects that have a “working mode”: a session may be closed, a file may already be saved and sealed, a report may already be finalized.

check() is about verifying the correctness of an object’s or variable’s state, and on failure it throws IllegalStateException.

Example: a “closed” expense tracker

Let’s add a class to our project that stores a list of expenses. We haven’t discussed collections of objects in depth yet, so we’ll keep it as simple as possible: a list plus a closed flag.

class ExpenseTracker {
    private val expenses: MutableList<Expense> = mutableListOf()
    private var closed: Boolean = false

    fun close() {
        check(!closed) { "Tracker already closed" }
        closed = true
    }

    fun add(expense: Expense) {
        check(!closed) { "Can't add expense: tracker is closed" }
        expenses.add(expense)
    }

    fun totalCents(): Int {
        var sum = 0
        for (e in expenses) sum += e.amountCents
        return sum
    }
}

Notice what we did: the input to add(expense) is valid as such (the Expense object is already guaranteed to be valid). But you can’t add it if the tracker is closed. That’s a state check.

How it looks in use

fun main() {
    val tracker = ExpenseTracker()
    tracker.add(Expense(500, "Coffee", "Latte"))
    tracker.close()

    println(tracker.totalCents()) // 500

    // tracker.add(Expense(100, "Snack", "Bar"))
    // If you uncomment: IllegalStateException from check(...)
}

Why this is good: the error tells you the problem isn’t with the expense and not with the “input,” but with the object’s lifecycle. That kind of bug is usually fixed not by “use another number,” but by “don’t call the method in this state.”

4. Messages and exception handling

Messages in require/check: how to make an exception useful

When beginners write require(x > 0) without a message, they assume “it’s obvious.” But two weeks later (or two hours later, if it’s been a rough day), you’ll see something like “Failed requirement.” in the console and try to remember which requirement it was and where exactly it failed.

Kotlin lets you write the message as a string or as a lambda { ... }. The lambda is convenient because it’s evaluated only if the check fails (so in the normal case it doesn’t waste resources).

A good message is almost always in the format: expected → got.

fun parseAmountCents(text: String): Int {
    val trimmed = text.trim()
    val value = trimmed.toIntOrNull()
    require(value != null) { "Amount must be an integer, got '$text'" }
    require(value > 0) { "Amount must be > 0, got $value" }
    return value
}

fun main() {
    println(parseAmountCents(" 150 ")) // 150
}

There are two different errors here: not a number, and a number but a bad one. And the messages are different — that saves your nerves during debugging.

And for check, the message should explain “why this state is forbidden”:

class Session {
    private var started: Boolean = false

    fun start() {
        check(!started) { "Session already started" }
        started = true
    }
}

This is an almost perfect minimal example: there are no arguments, and the operation is forbidden because of the state.

How to neatly combine require/check with a console main

Fail-fast is great inside your model, but a console app doesn’t have to crash with a “pretty stack trace” on the first user mistake. So a common approach is: require/check inside classes, and careful catching with a human-friendly message at the main level.

This is not a contradiction. It’s separation of responsibilities: the model says “you can’t do that,” and the CLI decides “how to explain that to the user.”

Let’s put together a small example: the user enters amount, category, and note, and we add an expense.

fun main() {
    val tracker = ExpenseTracker()

    try {
        print("Amount (cents): ")
        val amount = parseAmountCents(readln())

        print("Category: ")
        val category = readln()

        print("Note: ")
        val note = readln()

        tracker.add(Expense(amount, category, note))
        println("Added!") // Added!
        println("Total = ${tracker.totalCents()} cents") // Total = ... cents
    } catch (e: IllegalArgumentException) {
        println("Input error: ${e.message}")
    } catch (e: IllegalStateException) {
        println("App state error: ${e.message}")
    }
}

Here you can see the benefit of different exception types: we interpret IllegalArgumentException as an input problem, and IllegalStateException as a problem with the order of actions. That semantic separation is exactly why require and check exist in the first place.

5. Common mistakes when using require/check

Mistake #1: using check for user input.
This often happens out of habit: “well, I’m checking a condition, so it’s check.” But the meaning of check is different: it’s about “we ourselves brought the object into an impossible state.” If the user entered -5, that’s not “the object state is bad,” it’s “the argument is bad,” meaning require. Kotlin separates these cases and even throws different exceptions: require gives IllegalArgumentException, and check gives IllegalStateException.

Mistake #2: making messages useless (“bad input”, “error”, “oops”).
When you write a message like “wrong value,” you gain exactly zero seconds. The message should be a diagnosis: what was expected and what came in. The ideal format is “X must be …, got …”. It’s especially useful to include the actual value and the string length when validating text.

Mistake #3: placing checks too late, after changing state.
For example, a method manages to add an expense to the list, then checks that the tracker is closed, and crashes. The program crashed, but the data has already been partially mutated. That’s why require/check checks are almost always placed at the start of the method — before any changes. This makes the code predictable: either the operation is fully performed, or it isn’t started.

Mistake #4: trying to “fix everything” with normalization where strict validation is needed.
Sometimes you want to replace require(amount > 0) with “if it’s less than zero, make it zero.” But that turns errors into silent bugs. Normalization is useful for things like trim() and case normalization, but for key numbers and identifiers it’s often safer to fail fast: don’t create the object if it cannot exist by meaning.

Mistake #5: storing an invalid state in an object and hoping “we’ll fix it later”.
If your Expense can exist with an empty category, sooner or later you’ll forget to fix it, and it will survive until reporting, saving, or sorting. The rule “created means valid” greatly simplifies how you think about code. That’s why checks in init are not pedantry, but an investment in sleeping well.

1
Task
Kotlin SELF, level 31, lesson 4
Locked
Age validation
Age validation
1
Task
Kotlin SELF, level 31, lesson 4
Locked
Cents on a receipt
Cents on a receipt
1
Task
Kotlin SELF, level 31, lesson 4
Locked
Bank Account
Bank Account
1
Task
Kotlin SELF, level 31, lesson 4
Locked
Report builder
Report builder
1
Survey/quiz
Constructors and <code>init</code>, level 31, lesson 4
Unavailable
Constructors and init
Constructors and init
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION