Skip to content

Checkpoint: Typed Lookup

The Course
•
25 min study

Combine records, absence and explicit outcomes in a small lookup boundary. A valid request can find a title or miss it; malformed requests should be identified before lookup. This checkpoint uses the same map knowledge as intermediate and introduces no new library.

Understand the contract

First define the distinction in plain language. A blank ID is malformed. A nonblank ID missing from a map is a valid search with no match. A found title is data. Decide which representations belong to the public boundary: here three result variants make every caller handle the distinction.

The smaller example below uses Optional just for the absent/present part. Map.get returns null for absence because this map stores no null values. ofNullable converts that convention at one place. The caller remains responsible for display and does not mutate storage to produce a fallback.

For the independent task, preserve exact ID spelling after trimming surrounding spaces. Do not lowercase IDs unless the contract says that case is irrelevant. Rejecting input must leave the map unchanged. The input map and stored titles are nonnull; null lookup IDs are deliberately handled as malformed.

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.Map;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        Map<String, String> titles = Map.of("A1", "Read");
        Optional<String> found = Optional.ofNullable(titles.get("A1"));
        Optional<String> absent = Optional.ofNullable(titles.get("B2"));
        System.out.println(found.orElse("Missing"));
        System.out.println(absent.orElse("Missing"));
    }
}
Check your prediction
Text
Read
Missing

Trace a different case

Map.of creates an unmodifiable map and rejects null keys or values and duplicate keys. It is useful for a fixed example store, not for editable state. A rejected attempt to add a default proves why lookup should not manufacture data. For reports, do not infer an iteration-order guarantee from Map.of; this page only looks up explicit keys.

Compare the boundary case Java
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, String> titles = Map.of("A1", "Read");
        try {
            titles.put("B2", "Default");
        } catch (UnsupportedOperationException expected) {
            System.out.println("Store unchanged");
        }
        System.out.println(titles.size());
    }
}
Check your prediction
Text
Store unchanged
1

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 known IDFound with stored titleNormalization and map lookup
Unknown nonblank IDMissing, not InvalidOrdinary absence
Blank or null IDInvalid; store unchangedInput boundary

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: Typed Lookup: practice

Implement lookup(Map<String,String>, String) returning Found(title), Missing(id) or Invalid(message). Trim nonnull IDs; null/blank IDs return Invalid("id required"). Use a sealed Result interface. Demonstrate " A1 ", "B2" and " " using a display switch, producing Read, Missing B2 and id required. Check the map still has one entry.

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

Validate the request before asking the map. A missing key should not be grouped with malformed input.

Hint 2: a first step

Use get once after normalization; choose Found or Missing according to the returned reference.

Show one solution
Java
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, String> titles = Map.of("A1", "Read");
        System.out.println(display(lookup(titles, " A1 ")));
        System.out.println(display(lookup(titles, "B2")));
        System.out.println(display(lookup(titles, " ")));
        if (titles.size() != 1) {
            throw new AssertionError("lookup changed storage");
        }
    }

    static Result lookup(Map<String, String> titles, String id) {
        if (id == null || id.trim().isEmpty()) {
            return new Invalid("id required");
        }
        String key = id.trim();
        String title = titles.get(key);
        if (title == null) {
            return new Missing(key);
        }
        return new Found(title);
    }

    static String display(Result result) {
        return switch (result) {
            case Found found -> found.title();
            case Missing missing -> "Missing " + missing.id();
            case Invalid invalid -> invalid.message();
        };
    }
}

sealed interface Result permits Found, Missing, Invalid {}
record Found(String title) implements Result {}
record Missing(String id) implements Result {}
record Invalid(String message) implements Result {}

Expected output:

Text
Read
Missing B2
id required

The blank check comes first, so " " returns Invalid before trim produces an empty key that the map would just report as Missing. Missing carries the trimmed key, which is why the second line reads Missing B2 without padding. The display switch has no default: add a fourth Result record and this method stops compiling, which is the safety a sealed interface buys.

Change it and test again

Add a null ID, an empty store, and a lowercase a1 lookup. Write a check for each result variant before looking at its displayed text. Then deliberately remove trimming: your padded-ID case should fail. Restore the implementation and explain why tests of output alone may miss a wrongly classified outcome.

Explain before moving on

Could a single Optional express all three results without losing the reason? Which decisions belong in lookup and which belong in display? Finish this checkpoint without opening the implementation before moving to the numerical boundaries on Day 2.

Was this article helpful?

Your response is saved on this device.