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

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

Kotlin SELF
等級 14, 課堂 3
開放

1. Why split validation into a separate layer

If you have ever written code in the style “read a string → parse immediately → check the range immediately → print an error immediately → ask to repeat immediately”, then you already know how quickly everything turns into a textual labyrinth. And a labyrinth with a minotaur: you lose the logic, repeat chunks of code, and then you are afraid to touch the program because “what if it falls 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 percentage” (if we expect 0..100). That is, parsing succeeded, but the value is still “bad” — and that is where validation begins.

To keep this in mind, it helps to imagine the pipeline like this:

flowchart TD
    A["Syraia stroka iz readln()"] --> B[Normalizatsiia: 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 pipeline steps “composable”: 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 exactly T?? Because we need a single “failed” signal that is easy to handle in Kotlin.

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

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

Another important idea: a validator should usually be quiet. It does not print to the console and does not decide the fate of the program. It just answers: “valid or not?”. This makes it reusable. The same validator can be applied to an age, a discount percentage, or the number of attempts in a game — different scenarios, same range check.

And yes: inside a validator you often end up with a guard clauses style — consecutive 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 boundaries

Range checking is the most common validation example, because real data almost always has limits. Age cannot be -500, a percentage cannot be 250, and the width of a rectangle in our learning input should not be “0” if we expect at least 1.

Kotlin has a very readable form: x in min..max. It uses the range min..max and the in operator.

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 do not print “Error!”, we do not ask for input again, we do nothing dramatic. We simply return null if the value is not within the range.

Test it with an example:

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

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

Boundaries are part of the rule

Sometimes beginners get a little confused: does the range 1..100 include 100 or not? In Kotlin, a range created with .. includes both ends. That means 100 in 1..100 is true.

So you do not have to guess, it helps 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 is a different kind of rule. But today we lock in the basic variant: inclusive bounds.

Validator for Double in a range

You can validate Double in the same way. There is a nuance: Double is a floating-point type, but the in min..max check works in the same intuitive way (we compare numbers). In our course we have already discussed that Double can be “finicky” with ==, but comparisons with <, >, and in for ranges are normal practice for user 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 working with Double.

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

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

And yes, a simple thought helps here: 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.

“Not empty” validator for strings

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

Test it:

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

Why the validator returns the normalized string

Note: we return s, not raw. That means the validator in this example not only checks the rule, but also returns a string that has been “normalized”.

This is a good practice when the rule and normalization are logically tied together. If the rule is “the string must be non-empty after removing whitespace at the ends”, then it is natural to return exactly the version you checked. Then later in the program you do not carry extra spaces around, and you do not have to remember: “oh, I should have done trim() once more”.

5. Composition: readln() → parsing → validation

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

Parser and validator should not argue about roles

First — a clean parser (as 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)
}

Note: validateAgeOrNull is just a “semantic alias”. It makes scenario code more readable: when you see validateAgeOrNull, you do not think “what is 0..150?”, you think “okay, that is age”.

Connect the steps: readLine → parse → validate

We will not build “re-try input” with a loop yet (that is a separate topic and a separate habit), so we will use a simple strategy: if something fails, print a message and exit the program.

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

fun main() {
    val name = validateNonEmptyOrNull(readLine("Imia: "))
        ?: return println("Imia ne dolzhno byt' pustym.")

    val age = parseIntOrNull(readLine("Vozrast: "))
        ?.let(::validateAgeOrNull)
        ?: return println("Vozrast dolzhen byt' chislom ot 0 do 150.")

    println("Privet, $name! Tvoi vozrast: $age") // Privet, Alice! Tvoi vozrast: 20
}

Here one small “magic” appears: ?.let(::validateAgeOrNull). If you do not like let yet, you can write it more straightforwardly, without new constructs:

fun main() {
    val name = validateNonEmptyOrNull(readLine("Imia: "))
        ?: return println("Imia ne dolzhno byt' pustym.")

    val ageRaw = readLine("Vozrast: ")
    val ageParsed = parseIntOrNull(ageRaw) ?: return println("Vozrast: vvedite tseloe chislo.")
    val age = validateAgeOrNull(ageParsed) ?: return println("Vozrast: dopustimyi diapazon 0..150.")

    println("Privet, $name! Tvoi vozrast: $age")
}

Yes, there are a few more lines, but everything is maximally straightforward: parse first, then validate. For a beginner this is often the best option.

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

At this stage a temptation usually appears: “Let the validator also print an error, and ask again, and basically do everything for me”. I get it. It is like wanting a Swiss Army knife that also cooks borshch by itself. But in programming, such “combines” quickly become a problem.

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

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

One more thing: try to return the “normalized” variant of a value if normalization is required for the rule. With strings this is especially noticeable: if you validate the trim() version, it is logical to return it, so you do not carry spaces forward.

Mini library of validators for today

To reinforce the approach, let’s assemble a “set of building blocks” that we have effectively already written. This is not the final architecture of the day (that will come in the next lectures), but it is 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 checking x in min..max is a very “Kotlin-ish” way to express the idea “the value is inside the range”.

7. Typical mistakes when splitting validation into a separate layer

Mistake #1: mixing parsing and validation into one function that is “one and a half pages” long.
It is very easy to start with the idea “I will make one function readAge() and it will handle everything”, and after a couple of edits end up with 40 lines mixing trim(), toIntOrNull(), ranges, error messages, and special cases. Such code is hard to reuse and almost impossible to extend cleanly. Splitting into a “parser” and a “validator” looks like extra hassle exactly until you add a second input field and realize you are copying the same thing again and again.

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

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

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

Mistake #5: not agreeing on range boundaries and accidentally changing the meaning of the check.
Today you consider age 150 acceptable, tomorrow you do not, and you start changing checks manually in different places. A dedicated validator solves this problem: the rule lives in one place. And even more importantly, the code x in min..max reads unambiguously: inclusive bounds, which reduces the chance of an “off-by-one” mistake.

1
任務
Kotlin SELF, 等級 14, 課堂 3
上鎖
範圍過濾器
範圍過濾器
1
任務
Kotlin SELF, 等級 14, 課堂 3
上鎖
無空白的姓名
無空白的姓名
1
任務
Kotlin SELF, 等級 14, 課堂 3
上鎖
折扣規則
折扣規則
1
任務
Kotlin SELF, 等級 14, 課堂 3
上鎖
溫度感測器
溫度感測器
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION