Skip to content

Parsing as a Boundary

The Course
•
20 min study

External text needs both a documented format and a useful failure result. This lesson combines Day 1's sealed outcomes with the parsing rules from intermediate. A malformed record becomes a typed rejection with a line number; unexpected programming errors should remain visible.

Understand the contract

The small format is id;quantity, with exactly two fields and no quoting or embedded semicolons. split(";", -1) retains a missing final value as an empty field. Check shape before indexing, normalize fields, convert the integer, and apply the positive-quantity rule. The returned record represents validated data, not raw text.

A line number belongs to the input boundary because it describes where the raw value came from. It is not part of the item identity. The parser receives it explicitly so tests can supply a deterministic value. A result family keeps accepted data separate from rejection details without returning null or inventing a zero quantity.

Catch the exceptions that are documented outcomes of the conversion and validation. Do not catch Throwable, and do not turn every exception from a large application block into “invalid text.” A null record is deliberately rejected here, while a nonpositive line number is a caller error outside the parser's contract. The later importer counts physical lines, including skipped blanks.

The capstone also uses String.matches for one small decimal syntax rule. It matches the whole string against a regular expression. Read [0-9]{1,7}(\.[0-9]{1,2})? as one to seven digits, optionally followed by a literal dot and one or two digits. Square brackets choose a character, braces give a repetition range, parentheses group a part, and ? makes that group optional. The regex needs one backslash before the dot. In a Java string literal, write two backslashes to represent that one backslash, as the runnable example below shows. This bounded syntax check excludes exponent notation before constructing BigDecimal; the separate positive-value and maximum-amount checks still apply.

Before running, write the output you expect and explain which rule produces each line. Each editor is an independent program.

Predict, then run Java
public class Main {
    public static void main(String[] args) {
        System.out.println(describe(parse(" A ; 3 ", 1)));
        System.out.println(describe(parse("A;", 2)));
    }

    static Result parse(String line, int number) {
        if (line == null) {
            return new Rejected(number, "line required");
        }
        String[] fields = line.split(";", -1);
        if (fields.length != 2 || fields[0].trim().isEmpty()) {
            return new Rejected(number, "expected id;quantity");
        }
        try {
            int quantity = Integer.parseInt(fields[1].trim());
            if (quantity <= 0) {
                return new Rejected(number, "positive quantity required");
            }
            return new Parsed(new Item(fields[0].trim(), quantity));
        } catch (NumberFormatException error) {
            return new Rejected(number, "whole quantity required");
        }
    }

    static String describe(Result result) {
        return switch (result) {
            case Parsed parsed -> parsed.item().id() + ": " + parsed.item().quantity();
            case Rejected rejected -> "Line " + rejected.line() + ": " + rejected.message();
        };
    }
}

record Item(String id, int quantity) {}
sealed interface Result permits Parsed, Rejected {}
record Parsed(Item item) implements Result {}
record Rejected(int line, String message) implements Result {}
Check your prediction
Text
A: 3
Line 2: whole quantity required

Trace a different case

Separators inside a value need a format policy. Splitting cannot distinguish a separator that means “next field” from one intended as text unless you design escaping or quoting. Here extra fields reject. This is not a CSV parser, and using the name CSV would promise syntax the program does not implement. Keep a deliberately small format honest.

Compare the boundary case Java
public class Main {
    public static void main(String[] args) {
        String[] fields = "A;Read;notes".split(";", -1);
        System.out.println(fields.length == 2);
        String[] missing = "A;".split(";", -1);
        System.out.println(missing.length);
        System.out.println(missing[1].isEmpty());
    }
}
Check your prediction
Text
false
2
true

Read the decimal syntax check

Here 2.00 and 2 are allowed spellings, while an exponent and a third decimal place are rejected. The text 0 passes this syntax check but will still fail the domain's positive-amount check. Keep those two questions separate.

Check decimal spelling Java
public class Main {
    public static void main(String[] args) {
        String decimalPattern = "[0-9]{1,7}(\\.[0-9]{1,2})?";
        System.out.println("2.00".matches(decimalPattern));
        System.out.println("2".matches(decimalPattern));
        System.out.println("2e3".matches(decimalPattern));
        System.out.println("2.001".matches(decimalPattern));
        System.out.println("0".matches(decimalPattern));
    }
}
Check your prediction
Text
true
true
false
false
true

Keep syntax errors distinct from trusted values

A typed success result should contain data that has passed both spelling and meaning checks. A rejection should retain enough location information to fix the original input. Avoid returning a raw String labeled accepted if later code must still guess whether its number or enum name is valid.

Use a case table with one error per row: wrong field count, unknown category, invalid number spelling and out-of-range amount. A value such as 0 can pass decimal syntax and fail positivity. An exponent can describe a number mathematically while remaining outside this format's allowed spelling.

Do not expand the catch boundary to include unrelated application work. A null field caused by a programming mistake should not be reported as another malformed record. Keep the conversion/validation boundary narrow enough to explain which failures count as expected input rejection.

Build it yourself

Exercise

Parsing as a Boundary: practice

Parse a batch of study sessions in the format id;minutes. Write parseLine(String line, int number) returning Parsed(Session) or Rejected(line, message), with one message per rule:

  • not exactly two fields, or a blank ID: expected id;minutes;
  • minutes that are not a whole number: whole minutes required;
  • minutes outside 1 to 240: minutes must be 1 to 240.

Then loop over the batch in main. Skip blank lines, but count them, since line numbers are physical. Reject a repeated ID as duplicate id A, and keep going after every rejection. Predict the six output lines for the workspace's batch before you write code. The expected output is:

Text
Line 3: whole minutes required
Line 4: minutes must be 1 to 240
Line 5: expected id;minutes
Line 7: duplicate id A
Accepted: [Session[id=A, minutes=30], Session[id=E, minutes=15]]
Total: 45

The try block may contain only the integer conversion.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        String[] lines = {"A;30", "", "B;x", "C;0", "D;45;extra", " E ; 15 ", "A;10"};
        // For each nonblank line, call parseLine with its physical line number.
        // Print each rejection, skip duplicate IDs, then print the accepted list and total.
        System.out.println("Your workspace");
    }

    static Result parseLine(String line, int number) {
        // Check the shape, convert minutes inside a narrow try, then check the range.
        return new Rejected(number, "not written yet");
    }
}

record Session(String id, int minutes) {}
sealed interface Result permits Parsed, Rejected {}
record Parsed(Session session) implements Result {}
record Rejected(int line, String message) implements Result {}
Hint 1: the idea

There are two layers. parseLine judges one line on its own and knows nothing about the others. Duplicates are a batch rule, so they belong in main's loop, which also owns the line numbers and the running total.

Hint 2: a first step

Write parseLine first: split with -1, check fields.length, then declare int minutes; before a try that contains only Integer.parseInt. Do the range check after the try. In main, pass index + 1 as the line number.

Show one solution
Java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        String[] lines = {"A;30", "", "B;x", "C;0", "D;45;extra", " E ; 15 ", "A;10"};
        List<Session> accepted = new ArrayList<>();
        Set<String> seen = new HashSet<>();
        int total = 0;
        for (int index = 0; index < lines.length; index++) {
            if (lines[index].isBlank()) {
                continue;
            }
            Result result = parseLine(lines[index], index + 1);
            switch (result) {
                case Parsed parsed -> {
                    Session session = parsed.session();
                    if (seen.add(session.id())) {
                        accepted.add(session);
                        total += session.minutes();
                    } else {
                        System.out.println("Line " + (index + 1) + ": duplicate id " + session.id());
                    }
                }
                case Rejected rejected -> System.out.println("Line " + rejected.line() + ": " + rejected.message());
            }
        }
        System.out.println("Accepted: " + accepted);
        System.out.println("Total: " + total);
    }

    static Result parseLine(String line, int number) {
        String[] fields = line.split(";", -1);
        if (fields.length != 2 || fields[0].isBlank()) {
            return new Rejected(number, "expected id;minutes");
        }
        int minutes;
        try {
            minutes = Integer.parseInt(fields[1].trim());
        } catch (NumberFormatException error) {
            return new Rejected(number, "whole minutes required");
        }
        if (minutes < 1 || minutes > 240) {
            return new Rejected(number, "minutes must be 1 to 240");
        }
        return new Parsed(new Session(fields[0].trim(), minutes));
    }
}

record Session(String id, int minutes) {}
sealed interface Result permits Parsed, Rejected {}
record Parsed(Session session) implements Result {}
record Rejected(int line, String message) implements Result {}

Expected output:

Text
Line 3: whole minutes required
Line 4: minutes must be 1 to 240
Line 5: expected id;minutes
Line 7: duplicate id A
Accepted: [Session[id=A, minutes=30], Session[id=E, minutes=15]]
Total: 45

The catch surrounds only Integer.parseInt, so a NumberFormatException can mean just one thing, a bad minutes field. The range check and the record construction sit outside it, where a programming error would still surface. Line numbers come from the loop index, so skipping the blank line 2 does not shift later numbers; counting only nonblank lines would report B on line 2. The duplicate check runs on the parsed, trimmed ID after parsing succeeds, which is why A;10 is reported as a duplicate rather than as malformed.

Change it and test again

Widen the try in parseLine so it also covers the range check and new Parsed(...), and throw IllegalArgumentException for the range instead of returning: what must the catch now name, and which rejection could now hide a bug? Restore the narrow version. Add ;20 and F; and predict their messages. For the worked quantity parser, distinguish an invalid integer, zero and an extra field: they exercise different rules. Changing the display message must not change whether the result is accepted.

Explain before moving on

What is the difference between a parsing result and a display string? Why preserve line numbers separately from IDs? Explain which inputs the format cannot represent and why expanding the format requires tests, not just another split call.

Was this article helpful?

Your response is saved on this device.