CodeGym /Courses /Kotlin SELF /Validation as a separate layer: ranges, “not empty”, retu...

Validation as a separate layer: ranges, “not empty”, returning T?

Kotlin SELF
Level 14, Lesson 3
Available

1. Why separate validation into its own layer

If you’ve ever written code in the style “read a string → parse right away → check the range right away → print an error right away → ask to retry right away”, then you already know how quickly everything turns into a text maze. And a maze with a minotaur: you lose the logic, repeat chunks of code, and then you’re afraid to touch the program because “what if it breaks apart”.

The idea of a validation layer is simple: the parser is responsible for the format, and the validator is responsible for the rules.

For example, the string "12" can be parsed correctly into an Int, but still be wrong as “a kitten’s age in years” (if we expect 0..30) or wrong as “discount percent” (if we expect 0..100). In other words, parsing succeeded, but the value is still “bad” — and that’s where validation begins.

To keep this in mind, it’s convenient to imagine the pipeline like this:

flowchart TD
    A["Raw string from readln()"] --> B[Normalization: trim/lowercase]
    B --> C[Parsing: String -> T?]
    C --> D[Validation: T -> T?]
    D --> E[Scenario: use the value or show a message]

Note: both parsing and validation often return …?, i.e., a nullable type. This makes the pipeline steps “connectable”: any step can say “didn’t work” via null, and the next level decides what to do next.

2. Validator: what it is and why it returns T?

A validator is a small function that receives an already parsed value and checks it against a rule. If the rule holds, it returns the value (usually the same one). If not, it returns null.

Why T? specifically? Because we need a single “didn’t pass” signal that is easy to handle in Kotlin.

For example, a “number in range” validator can have the following semantic signature:

  • input: Int, bounds min, max
  • output: Int? — either the same number or null

Another important idea: a validator should usually be silent. It doesn’t print to the console and doesn’t decide the program’s fate. It simply answers the question: “valid or not?”. This makes it reusable. The same validator can be applied to age, discount percent, or the number of attempts in a game — scenarios differ, but the range check is the same.

And yes: inside a validator you often end up with a guard clauses style — a sequence of checks with early returns. It reads like plain text: “if below minimum — not OK; if above maximum — not OK; otherwise OK”.

3. Numeric ranges: in, min..max, and bounds

Range checking is the most common validation example, because real data almost always has bounds. Age can’t be -500, percent can’t be 250, and a rectangle width in our learning input shouldn’t be “0” if we expect at least 1.

In Kotlin, there’s a very readable form: x in min..max. It uses the range min..max and the in operator.

A validator for Int in a range

Let’s start with a simple function:

fun validateIntInRangeOrNull(x: Int, min: Int, max: Int): Int? {
    if (x !in min..max) return null
    return x
}

Notice what matters here: we don’t print “Error!”, we don’t ask for input again, we don’t do anything dramatic. We simply return null if the value didn’t land in the range.

Let’s test it:

fun main() {
    val a = validateIntInRangeOrNull(10, 1, 100)
    val b = validateIntInRangeOrNull(0, 1, 100)

    println(a) // 10
    println(b) // null
}

Bounds are part of the rule

Sometimes beginners get “a little” confused: does the range 1..100 include 100 or not? In Kotlin, the .. range includes both bounds. That is, 100 in 1..100 is true.

So you don’t have to guess, it’s useful to keep a small table:

Rule Example Result
x in 1..3
1 in 1..3
true
x in 1..3
3 in 1..3
true
x in 1..3
0 in 1..3
false
x in 1..3
4 in 1..3
false

If you need “strictly less” or “strictly greater”, that’s a different kind of rule. But today we’re fixing the baseline variant: inclusive bounds.

A validator for Double in a range

You can validate a Double the same way. There’s a nuance: Double is a floating-point type, but the in min..max check will work in the same intuitive way (we compare numbers). In our course we already discussed that Double can be “picky” for ==, but comparisons like <, >, and in for ranges are normal practice for user-facing constraints.

fun validateDoubleInRangeOrNull(x: Double, min: Double, max: Double): Double? {
    if (x < min) return null
    if (x > max) return null
    return x
}

Here I intentionally showed a version without in, so you can see that “under the hood” the idea is the same: two comparisons. Sometimes this variant reads even clearer when you work with Double.

4. Strings: checking “not empty” after trim()

The “string must not be empty” check seems simple… until you see input like " " (four spaces). Formally it’s not an empty string, but semantically the user “entered nothing”. That’s why in real programs the “not empty” rule almost always means: first trim(), then check emptiness.

And yes, a simple idea often helps: the parser answers “string → value”, and the validator answers “does the value fit?”. A string is also a value, so it can be validated too.

A “not empty” validator for strings

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

Let’s test it:

fun main() {
    println(validateNonEmptyOrNull("Alice"))   // Alice
    println(validateNonEmptyOrNull("   "))     // null
    println(validateNonEmptyOrNull(""))        // null
}

Why the validator returns the normalized string

Notice: we return s, not raw. In other words, in this example the validator not only checks the rule, but also returns a string “brought into a normal form”.

This is a good practice when the rule and normalization are logically tied. If our rule sounds like “the string must be non-empty after removing whitespace at the edges”, then it’s natural to return exactly the variant we checked. Then later in the program you don’t carry extra spaces around, and you don’t have to remember: “oh, I should have done trim() again”.

5. Composition: readln() → parsing → validation

The nicest part begins when you put everything into a chain. We’ll make a small learning scenario: a “mini form” that asks for a name and an age, then prints a greeting. The main goal is not the form itself, but for you to see: validation is a separate layer, and you can plug it in like a LEGO brick.

The parser and the validator should not argue about roles

First — a pure parser (like we did in the previous lecture):

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

Now the validator:

fun validateAgeOrNull(age: Int): Int? {
    return validateIntInRangeOrNull(age, 0, 150)
}

Notice: validateAgeOrNull is just a “semantic alias”. It makes the scenario code more readable: when you see validateAgeOrNull, you don’t think “what is 0..150?”, you think “okay, that’s age”.

Connecting steps: readLine → parse → validate

We won’t build “repeated input” with a loop yet (that’s a separate topic and a separate habit), so we’ll use a simple strategy: if something didn’t work — print a message and terminate the program.

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

fun main() {
    val name = validateNonEmptyOrNull(readLine("Name: "))
        ?: return println("Name must not be empty.")

    val age = parseIntOrNull(readLine("Age: "))
        ?.let(::validateAgeOrNull)
        ?: return println("Age must be a number from 0 to 150.")

    println("Hello, $name! Your age: $age") // Hello, Alice! Your age: 20
}

Here a little “magic” appears: ?.let(::validateAgeOrNull). If you don’t like let yet, you can write it more “straight”, without new constructs:

fun main() {
    val name = validateNonEmptyOrNull(readLine("Name: "))
        ?: return println("Name must not be empty.")

    val ageRaw = readLine("Age: ")
    val ageParsed = parseIntOrNull(ageRaw) ?: return println("Age: enter an integer.")
    val age = validateAgeOrNull(ageParsed) ?: return println("Age: valid range is 0..150.")

    println("Hello, $name! Your age: $age")
}

Yes, there are a few more lines, but everything is as straightforward as possible: parsed, then validated. For a beginner, this is often the best option.

6. How not to turn validators into a “combine harvester”

At this stage, temptation usually appears: “Let’s make the validator print the error, and re-prompt by itself, and generally do everything for me”. I get it. It’s like wanting a Swiss Army knife that also cooks soup. But in programming, such “harvesters” quickly become a problem.

A rule that saves your sanity: the validator should be small, predictable, and reusable. It takes a value, checks a rule, returns either the value or null. It shouldn’t know where the value came from (console, test, file) and what happens next.

Naming discipline also helps. If a function can return null as “didn’t pass”, it should be visible from the name: the OrNull suffix is a great contract with your future self. And future you is still you, just tired, at 2:30 a.m., before a deadline.

One more thing: try to return a “normalized” version of the value if normalization is needed for the rule. With strings it’s especially noticeable: if you validate the trim() version, then it makes sense to return it, so you don’t drag spaces further along.

A mini validator library for today

To reinforce the approach, let’s assemble a “set of building blocks” that we’ve effectively already written. This is not the final architecture of the day (that will be in the next lectures), but it’s a good intermediate form: validators separately, parsers separately.

fun validateIntInRangeOrNull(x: Int, min: Int, max: Int): Int? {
    if (x !in min..max) return null
    return x
}

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

fun validateDoubleInRangeOrNull(x: Double, min: Double, max: Double): Double? {
    if (x < min) return null
    if (x > max) return null
    return x
}

Notice that x in min..max is a very “Kotlin-ish” way to express the idea “the value is inside the range”.

7. Typical mistakes when separating validation into its own layer

Mistake No. 1: mixing parsing and validation into one “page and a half” function.
It’s very easy to start with the idea “I’ll make one function readAge() and it will handle everything”, and after a couple of edits end up with 40 lines where trim(), toIntOrNull(), ranges, error messages, and special cases are all mixed together. Such code is hard to reuse and almost impossible to extend neatly. Splitting into “parser” and “validator” looks like extra hassle right up until you add a second input field and realize you’re copying the same thing over and over.

Mistake No. 2: the validator prints messages to the console.
When a validator starts doing println("Error!"), it loses universality. Today you want one wording, tomorrow another, the day after tomorrow you don’t even have a console but tests, where output is not needed. It’s much calmer when the validator simply returns null, and the scenario decides “what to tell the user”. Then you don’t get a “voice inside the program’s head” that suddenly starts speaking in the wrong tone.

Mistake No. 3: “magic values” instead of null.
Sometimes instead of null people return -1 or an empty string, thinking it’s “simpler”. The problem is that -1 might be a real value (for example, in a different task), and an empty string might be valid input in some context (for example, an optional field). null honestly means “value not obtained / didn’t pass validation”, and Kotlin helps you not forget to handle it.

Mistake No. 4: checking “not empty” without trim().
If you check only raw.isEmpty(), then a string of spaces will pass as “not empty”. The user will be sure they “entered nothing”, and the program will think “everything is great, name is set”. That’s why the “not empty” rule almost always should be understood as “not empty after removing whitespace at the edges”, and you should return the trim() version.

Mistake No. 5: not agreeing on range bounds and accidentally changing the meaning of the check.
Today you consider age 150 allowed, tomorrow you don’t, and you start changing checks manually in different places. An extracted validator solves this problem: the rule lives in one place. And even more importantly, x in min..max reads unambiguously: an inclusive range, which reduces the chance of an “off-by-one” error.

1
Task
Kotlin SELF, level 14, lesson 3
Locked
Range filter
Range filter
1
Task
Kotlin SELF, level 14, lesson 3
Locked
Name without extra spaces
Name without extra spaces
1
Task
Kotlin SELF, level 14, lesson 3
Locked
Discount by the rules
Discount by the rules
1
Task
Kotlin SELF, level 14, lesson 3
Locked
Temperature sensor
Temperature sensor
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION