The TiffinBox BuildOne system, every chapter
0 / 0

Workbench / The TiffinBox Build

S37 · V3·36

Typed Keys

Volume 3, chapter 36. The log's extensions were a Map<Integer, byte[]> and four int constants, so every reader decoded bytes by hand and nothing stopped one from reading the pricing tag as a customer id. It compiled and printed "customer = 1790;false;Welcome". Worse, the log accepted a malformed idempotency key as raw bytes, said it was durable, and then refused to open on the next start. This stage replaces the map with a type-safe heterogeneous container: Tag<T> keys that carry their number, type and codec, the same 117 bytes on disk, no unchecked casts, and a server form that no longer returns Object.

6 parts · ~4 min to read
Updated Suggest a correction

Stage 37: typed keys

The brief

What you'll build.

  • Extensions (core): an immutable container of tag numbers and bytes, read and written through Tag<T>(number, name, Codec<T>): <T> Optional<T> get(Tag<T>), <T> Extensions with(Tag<T>, T); codecs for UTF-8, ASCII and epoch milliseconds; arrays copied in and out; unknown numbers kept as bytes;
  • the tags: OrderCodec.IDEMPOTENCY_KEY (Tag<IdempotencyKey>), RECEIVED_AT (Tag<Instant>), CUSTOMER (Tag<String>) in core, Server.Pricing.TAG (Tag<Pricing>) in the server, which is the module that understands pricing;
  • the codec and log: OrderCodec.encode(Order, Extensions), Decoded(Order, Extensions), OrderLog.append(..., Extensions), Recovered.firstExtensions as Map<String, Extensions>;
  • the form: Pages.draft returns a sealed Validated<Draft> (Valid or Invalid) instead of Object, removing two @SuppressWarnings("unchecked");
  • tests: ExtensionsTest (4), a server test that no tag number is used twice, and the log bytes compared before and after.

Why a real company needs this. Wire formats outlive the code that writes them. When every reader decodes bytes by hand, one reader with the wrong tag or the wrong charset produces wrong data quietly, and one writer with bad bytes produces a file the next release can't read. Typed keys put the decoding in one place per field, next to its number.

Why now. Chapter 36 is generics: generic types and methods, bounds, variance and wildcards, erasure and its consequences, and other languages' strategies. Map<Integer, byte[]> is the untyped design generics exist to replace, and its fix, a typed key, is a generic pattern the chapter leaves out (type-safe heterogeneous containers).

What you'll have at the end.

  • extensions the compiler type-checks at every read and write;
  • a malformed value refused when it's written, not when the log is reopened;
  • zero unchecked casts in core and server;
  • ADR-0039: typed keys for extensible formats.

Theory to own

  1. Type-safe heterogeneous containers. How can one container hold a String, an Instant and a Pricing, and still give each back with its own type? (Companion, Explain it differently 2; Effective Java, item 33.)
  2. Erasure. At run time, is a Tag<String> distinguishable from a Tag<Instant>? What follows for casts? (The chapter, "Type erasure"; Companion, Gaps 2.)
  3. Sealed generic types. What does sealed interface Validated<T> give a caller that Object and instanceof List<?> don't? (The chapter, "Generic classes".)
  4. Compatibility. Why must the numbers stay exactly as stages 8 and 11 wrote them? (Volume 1, stage 8.)

Build it

Step 1: record what the bytes are now

Write exp/37/Bytes.java: one order with all four extensions and an unknown tag 99, encoded with the stage 36 code, printed as hex, decoded back.

Checkpoint. exp/37/bytes-before.out.

Step 2: typed tags

Write Extensions, Tag<T> and Codec<T>; change OrderCodec, OrderLog, the server and tbx to use them; define Pricing.TAG in the server. Run the experiment again with the new API.

Checkpoint. bytes-after.out identical to bytes-before.out; 51 core and 42 server tests; golden master: 47 exchanges, identical.

Step 3: one number, one meaning

Collect every tag (OrderCodec.TAGS plus Pricing.TAG) in a server test and check the numbers are distinct and are exactly 1 to 4.

Checkpoint. everyExtensionTagHasItsOwnNumber passes.

Step 4: no more Object

Replace Object draft(...) in Pages with Validated<Draft>, and the two instanceof List<?> plus unchecked casts with a switch.

Checkpoint. grep -rn '@SuppressWarnings("unchecked")' core/src server/src finds nothing; the suite passes 44 tests.

Senior and architect lens

1. Make the format's extension point typed, not its storage. The bytes and numbers are unchanged; only the way code reaches them changed. That's what made this a refactor (identical bytes, identical golden master) rather than a migration.

2. ADR-0039: typed keys for extensible formats. Write it with these points:

  • Keys: every extension is a Tag<T> with a number, a name and a codec, declared in the module that owns its type.
  • Numbers: permanent; never reused; every tag listed in OrderCodec.TAGS or its module's list, checked by a test.
  • Validation: values are validated when built (IdempotencyKey's constructor), so a bad value can't be written.
  • Unknown tags: kept as bytes and written back unchanged.
  • Casts: no @SuppressWarnings("unchecked") without a comment proving the cast safe; none today.

3. A file that can't be opened is worse than a request that fails. The old path turned a writer's mistake into a startup failure on the next deploy, far from the cause. Validating at write time moves the failure to the request that caused it.

What breaks first, and when it's addressed:

Pressure What breaks Where it's addressed
a known tag with bad bytes on disk recovery still throws from open() stage 41 (JVM: failure handling at startup), stage 50 (persistence: migrations)
null everywhere else pricing.get(id) can still be null stage 46 (API validation), stage 49 (typed request bodies)
tags across services other services can't see Tag types stage 46 (contract-first schemas)
tag numbers reused by a new module only listed tags are checked stage 44 (build system: a registry check)

Evidence

  • exp/37/bytes-before.out and bytes-after.out are identical; restart-before.out shows the reopen failure.
  • 51 core and 42 server tests pass; golden master: 47 exchanges, identical; the suite passes 44.
  • No @SuppressWarnings("unchecked") in core or server.
  • ADR-0039 is committed.

Carry forward

  • Extensions and Tag<T> are how the log grows (stage 50 adds tags for persistence metadata).
  • Validated<T> is the shape for form and request validation (stage 46).
  • Values validated at construction is the rule for anything that will be written down.