Skip to content

Checkpoint: Import Preview

The Course
•
25 min study

Build a preview before changing any stored state. A preview collects valid IDs or line-specific errors from bounded input. If any error exists, callers receive the errors and no accepted list. This prepares the all-or-nothing boundary used by the final ledger.

Understand the contract

Choose the complete policy first: at most four supplied lines, trim each line, skip blanks, accept nonblank IDs without semicolons, and reject duplicate normalized IDs. Physical line numbers come from the array index plus one. The input array is nonnull; a null entry is an invalid record with its own line number.

A preview is a value, not a partially changed repository. Build local candidate data and errors, then return Accepted or Rejected. Use defensive copies in both result records so the caller cannot edit a result after it has been checked. No global counters or shared lists are needed.

This exercise limits the number of array elements, not the length of each string; the final project adds both limits. Keep error reporting predictable by scanning input order. A preview with errors deliberately withholds the candidate list so a caller cannot accidentally commit the valid subset.

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

Predict, then run Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        String[] lines = {" A ", " ", "B"};
        List<String> accepted = new ArrayList<>();
        for (int index = 0; index < lines.length; index++) {
            String id = lines[index].trim();
            if (!id.isEmpty()) {
                accepted.add(id);
                System.out.println("Line " + (index + 1) + ": " + id);
            }
        }
    }
}
Check your prediction
Text
Line 1: A
Line 3: B

Trace a different case

An error result is also a collection-ownership boundary. Copying only accepted data while exposing the mutable error list would let later edits change what a user thinks was validated. The record below preserves a snapshot even when the builder is cleared. Error strings are immutable; no deep copy is needed for them.

Compare the boundary case Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        List<String> errors = new ArrayList<>();
        errors.add("Line 2: duplicate");
        Rejected result = new Rejected(errors);
        errors.clear();
        System.out.println(result.errors());
    }
}

record Rejected(List<String> errors) {
    Rejected {
        errors = List.copyOf(errors);
    }
}
Check your prediction
Text
[Line 2: duplicate]

Plan your acceptance cases

Before writing the complete implementation, predict these cases without running the solution. Keep the requirements above as the authority; this table highlights distinct promises rather than prescribing a particular class layout.

CaseExpected behaviorSkill it checks
Padded IDs with blank physical lineNormalize IDs and keep physical positionsInput boundary
Duplicate on physical line 3Rejected with line 3 messageIdentity after normalization
Four lines, then five linesAccept at limit; reject above itInclusive limit

After your first version works, choose one row and introduce a plausible defect that it should expose. Restore the correct version, then recreate the central operation without the worked example. If one skill is missing, revisit that lesson before combining more features.

Build it yourself

Exercise

Checkpoint: Import Preview: practice

Implement the preview contract above with sealed Preview, Accepted(List<String>) and Rejected(List<String>). For [" A ","B"] display [A, B]. For ["A"," ","A"] display [Line 3: duplicate]. More than four lines returns a rejection with "too many lines". Keep malformed and duplicate errors in physical-line order.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        // Add your implementation and checks below.
        System.out.println("Your workspace");
    }
}
Hint 1: the idea

Use a set to detect duplicates after trimming and collect errors separately from accepted IDs.

Hint 2: a first step

Return only one result variant at the end: no errors means Accepted, otherwise Rejected.

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

public class Main {
    public static void main(String[] args) {
        System.out.println(display(preview(new String[] {" A ", "B"})));
        System.out.println(display(preview(new String[] {"A", " ", "A"})));
    }

    static Preview preview(String[] lines) {
        if (lines.length > 4) {
            return new Rejected(List.of("too many lines"));
        }
        List<String> ids = new ArrayList<>();
        List<String> errors = new ArrayList<>();
        Set<String> seen = new HashSet<>();
        for (int index = 0; index < lines.length; index++) {
            String line = lines[index];
            String prefix = "Line " + (index + 1) + ": ";
            if (line == null || line.contains(";")) {
                errors.add(prefix + "invalid id");
                continue;
            }
            String id = line.trim();
            if (id.isEmpty()) {
                continue;
            }
            if (!seen.add(id)) {
                errors.add(prefix + "duplicate");
            } else {
                ids.add(id);
            }
        }
        if (!errors.isEmpty()) {
            return new Rejected(errors);
        }
        return new Accepted(ids);
    }

    static String display(Preview preview) {
        return switch (preview) {
            case Accepted accepted -> accepted.ids().toString();
            case Rejected rejected -> rejected.errors().toString();
        };
    }
}

sealed interface Preview permits Accepted, Rejected {}
record Accepted(List<String> ids) implements Preview {
    Accepted {
        ids = List.copyOf(ids);
    }
}
record Rejected(List<String> errors) implements Preview {
    Rejected {
        errors = List.copyOf(errors);
    }
}

Expected output:

Text
[A, B]
[Line 3: duplicate]

The line-count check comes first, so an oversized input is rejected without doing any per-line work. Line numbers come from the loop index, not from the number of IDs accepted, so the blank line 2 still counts and the duplicate is reported as line 3. Errors are collected rather than thrown, so every problem is reported in order; the records copy their lists so callers cannot change them.

Change it and test again

Test four versus five lines, all blanks, null entries, and padded duplicates. Inspect the result variant rather than just printed text. Try clearing each returned list and confirm it is unmodifiable. A rejected preview should expose errors without giving the caller a valid subset to commit accidentally.

Explain before moving on

How does this preview differ from an importer that changes storage while reading? Which policies belong to the input format, and which to a later repository? Explain why an all-blank file is an empty accepted preview under this contract.

Was this article helpful?

Your response is saved on this device.