1. Fail-fast and the difference between require and check
Why “fail earlier” at all: the fail-fast idea
If you are just starting out, it may seem that a good program should be polite and patient: “well, the user entered nonsense — let’s quietly substitute 0, an empty string, and somehow keep going”. In practice, this “kindness” often turns into error accumulation: the program keeps running, but the data becomes garbage, and eventually everything breaks… only much later and much less clearly.
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 complete, here is a small diagram (this is about “meaning”, not syntax):
flowchart TD
A[Received data] --> B{Is the data usable?}
B -- No --> C[Fail-fast: require/check -> exception]
B -- Yes --> D[Continue logic]
D --> E{Is the state correct?}
E -- No --> F[Fail-fast: check -> exception]
E -- Yes --> G[Result is predictable]
The biggest fail-fast bonus in a learning project: you stop guessing “why it computes weirdly”, and start getting answers like “Age must be >= 0, got -5”. It’s surprising how much this reduces the urge to throw a laptop out the window (I checked; the window is not to blame).
require vs check: looks similar, different meaning
From the outside, require(condition) and check(condition) look almost the same: 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 reads the code after you.
require() is used to validate input arguments, while check() is used to validate the state of an object or a variable. When require() fails, it throws IllegalArgumentException, and when check() fails, it throws IllegalStateException.
Let’s summarize in a table (it’s genuinely worth keeping in mind):
| The question you ask | What to use | Typical thought | Exception |
|---|---|---|---|
| “I was given bad data; I can’t continue” | |
“The argument is wrong” | |
| “The data is fine, but the object is currently in an impossible/forbidden state” | |
“The state is wrong” | |
A very rough but memorable analogy: require is the face control at the club entrance (“no sneakers”), and check is the security inside (“no toaster in the pool”). If you feel like “both are ‘not allowed’”, you’re right. But the reasons for “not allowed” are different.
2. require: protecting the input
When you create an object, you want it to be correct immediately. This is a key beginner-level OOP idea: if an object exists, you can trust it. In Kotlin, a typical way to do this is to place checks in init { ... } or directly in constructor logic.
Minimal example of require in init
Let’s start with something as simple as possible so your hand gets used to it:
class Age(val value: Int) {
init {
require(value >= 0) { "Age must be >= 0, got $value" }
}
}
fun main() {
println(Age(10).value) // 10
}
Here we fixed a rule: age cannot be negative. Importantly, we’re not trying to “fix” it — we forbid creating an invalid object. And that’s normal: if you get -10, it’s not “almost an age”, it’s an input error.
Example from the learning project: 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 an Expense object to be unable to exist in a garbage form.
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}" }
}
}
Note the style: the message should explain what was expected and what was received. This is not 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 usually means we failed to parse a number somewhere or mixed up the currency.
require is also suitable for regular methods
Preconditions are needed not only when creating objects. If you have a method that receives arguments from outside, you can also protect the input with require: it’s precisely about arguments without which the function cannot work.
Imagine we have a service 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, you could “silently” turn -5 into 0. But then you lose the signal that something is wrong somewhere.
3. check: protecting the object state
Now let’s move on to check. It’s needed when input data is fine, but the object itself should not perform the operation in its current state. This often appears in objects with a “mode of operation”: a session may be closed, a file may already be saved and “sealed”, a report may already be finalized.
check() is for validating the correct state of an object or variable, 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 object collections deeply yet, so we’ll keep it very simple: 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
}
}
See what we did: the input to add(expense) is valid as such (the Expense object is already guaranteed valid). But you cannot add it if the tracker is closed. That is 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 uncommented: IllegalStateException from check(...)
}
Why this is good: the error tells you the problem is not with the expense and not with “input”, but with the object lifecycle. This 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 the day was rough), you’ll see something like “Failed requirement.” in the console and try to remember which requirement and where exactly it failed.
Kotlin lets you write the message as a string or as a lambda { ... }. A lambda is convenient because it’s evaluated only if the check fails (so in the normal case it doesn’t spend 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
}
These are two different errors: not a number, and a number but invalid. And the messages differ — this 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 almost an ideal minimal example: no arguments, and the operation is forbidden because of state.
How to neatly combine require/check with a console main
Fail-fast is great inside your model, but a console application does not have to crash with a “pretty stacktrace” on the first user mistake. So a common pattern is: inside classes — require/check, and at the main level — neat catching and a human-friendly message.
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 it to the user”.
Let’s assemble a small example: the user enters an amount, a category, a 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 exceptions: we interpret IllegalArgumentException as an input problem, and IllegalStateException as an order-of-actions problem. That is exactly the semantic separation for which 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 check”. But check has a different meaning: it’s about “we ourselves drove the object into an impossible state”. If the user entered -5, that’s not “the object state is bad”, that’s “the argument is bad”, i.e., require. Kotlin separates these cases and even throws different exceptions: require gives IllegalArgumentException, and check gives IllegalStateException.
Mistake #2: writing useless messages (“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 arrived. 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, the method managed to add an expense to the list, then checked that the tracker is closed, and crashed. It crashed, but the data has already been partially changed. That’s why require/check checks are almost always placed at the start of a method — before any changes. This makes the code predictable: either the operation is fully done, or it never 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 below zero — make it zero”. But that turns errors into silent bugs. Normalization is useful for things like trim() and case folding, 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: keeping an invalid state inside 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 live long enough to reach reporting, saving, or sorting. The rule “created means valid” greatly simplifies how you think about the code. That’s why checks in init are not nitpicking — they’re an investment in sleeping well.
GO TO FULL VERSION