The TiffinBox BuildOne system, every chapter
0 / 0

Workbench / The TiffinBox Build

S1 · V1·01

The Toolbox and the First Tool

Volume 1, chapter 01. TiffinBox starts as a repository and one honest command-line tool, `tbx orders stats`: it reads a day's orders, totals them in integer paise, reports bad lines on stderr, and speaks a documented exit-code contract. You'll make the first decisions that every later stage relies on (money as integers, a pure core with an I/O shell, a CLI as an API, decisions written down) and meet a real locale bug that corrupts JSON.

7 parts · ~11 min to read
Updated Suggest a correction

Stage 1: the toolbox and the first tool

The brief

What you'll build. The TiffinBox repository, and its first program: a command-line tool that summarises a day's orders.

Terminal
$ tbx orders stats samples/day1.csv
tbx: line 4: skipped: invalid amount 'lunch'
tbx: line 5: skipped: invalid amount '1e3'
tbx: line 8: skipped: expected 3 fields, got 2
orders=3 total=450.00 average=150.00 skipped=3
$ echo $?
65

It reads lines of order_id,kitchen_id,amount from a file or stdin, counts the valid orders, totals them, and prints the average. Bad lines are reported on stderr with their line numbers. The exit code says whether the input was clean. --json prints the same result for other programs to read.

Why a real company needs this. Every food business reconciles the day: how many orders, how much money, which records were broken. Before TiffinBox has a server or a database, the owner of a tiffin centre exports orders from a billing app as CSV, and someone has to total them correctly. Small internal tools like this are also where most engineers' code meets real, messy data first, and where silent errors (a float rounding a rupee away, a bad line quietly counted as zero) cost real money.

Why this is the right first stage. Chapter 01 is about the toolbox: terminals, paths, standard streams, exit codes, compiling and running, and reading errors. A CLI exercises every one of those. It also lets you make the system's first architectural decisions while the code is small enough to change cheaply:

  • how money is represented;
  • where the logic lives (separate from input and output);
  • what the tool promises to its callers;
  • how decisions are recorded.

What you'll have at the end.

  • a tiffinbox Git repository with a layout that the next 200 chapters can grow into;
  • tbx, a Java 21 tool with a strict amount parser, a pure core, and a documented CLI contract;
  • a build script that compiles with warnings as errors, runs checks, and produces a reproducible JAR;
  • two decision records (ADRs), and a README with the stage's evidence.

Theory to own

Answer each question in your own words before you build. Each one is something the build depends on, and each points to the part of chapter 01 that covers it.

  1. Streams. Why should the summary go to stdout and the "skipped" messages to stderr? What breaks for a caller who runs tbx orders stats day.csv > summary.txt if you mix them? (Chapter: "Your first commands", standard input and output.)
  2. Exit codes. Why is the exit code part of the tool's interface, as much as its output? What does a shell script do with tbx … && upload.sh? (Chapter: exit codes.)
  3. Paths. If someone runs tbx orders stats samples/day1.csv from a different folder, what happens? Who decides what a relative path is relative to? (Chapter: files, folders and paths.)
  4. Bits and meaning. The text 149.50 is six bytes. What has to happen before it's a number, and why is "what counts as a number" a decision rather than a fact? (Chapter: bits and bytes; the Companion's table of five averaging programs that disagree.)
  5. Compile, build, run. What does javac --release 21 guarantee, and what does -Werror change about which mistakes can reach a user? (Chapter: programming languages; the edit, build, run loop.)
  6. Errors. Which of the chapter's three kinds of error can a build script catch, which can checks catch, and which can only a person catch? (Chapter: three kinds of errors.)

Build it

Work through the steps in order. Each checkpoint asks you to produce something before you open the reference solution. Your version will differ, and should. The solutions show one defensible way and the real output it produced.

Step 1: set up the repository

Install JDK 21 and Git (the chapter's "Installing the languages"), then create this layout:

Text
tiffinbox/
├── README.md                    what TiffinBox is; how to build; each stage's evidence
├── docs/
│   └── adr/
│       ├── 0001-record-architecture-decisions.md
│       └── 0002-tbx-cli-contract.md
└── tools/
    └── tbx/
        ├── build.sh             compile, check, package; fails loudly
        ├── samples/             small hand-made input files
        ├── src/in/tiffinbox/tbx/
        └── test/in/tiffinbox/tbx/

Commit after each step from here on. Volume 8 covers Git properly; for now, small commits with clear messages are enough.

Checkpoint 1. Why in.tiffinbox.tbx for the package, and why is tools/tbx/ a folder of its own rather than the repository root?

Step 2: write the contract before the code

Write docs/adr/0002-tbx-cli-contract.md. Decide and write down:

  • the command line: arguments, options, where input comes from;
  • the input format: fields, separators, comments and blank lines;
  • what a valid amount is, exactly;
  • what goes to stdout, and in which formats;
  • what goes to stderr;
  • every exit code and its meaning;
  • what happens with an empty input.

Checkpoint 2. Write the ADR. Use four headings: Context, Decision, Consequences, Revisit when.

Step 3: parse money strictly

Write Paise.parse(String) → Optional<Long> that turns "149.50" into 14950, accepts "149.5" and " 120 ", and rejects everything your contract excludes. Then write Paise.format(long) → String.

Checkpoint 3. Before writing the parser, write down at least ten inputs it must reject. Then implement it.

Step 4: keep the logic pure

Put the arithmetic in a small type that knows nothing about files, streams or the command line:

  • Stats(count, totalPaise);
  • add(paise) returns a new Stats;
  • averagePaise() returns the average, rounded to a whole paisa.

Checkpoint 4. Decide how the average is rounded (₹1.45 over 2 orders is 72.5 paise), what happens when the total overflows, and what averagePaise() does with zero orders. Implement it without floating point.

Step 5: the shell around the core

Write Main: parse the arguments, open the file or stdin as UTF-8, read line by line, call the core, print one result line, and return the exit code from your contract. Make run(args, out, err) return the code instead of calling System.exit, so checks can call it.

Checkpoint 5. Implement it, then run it on a clean file, a messy file, a missing file, bad arguments and empty input. Finally, run it once with java -Duser.language=mr -Duser.country=IN -Dstdout.encoding=UTF-8 -jar tbx.jar orders stats --json samples/clean.csv. What do you expect, and what do you get?

Step 6: a build that fails loudly

Write build.sh and a small checks program. The script compiles with warnings as errors, runs the checks, packages a JAR, and stops at the first failure. No test framework yet: chapter 2 introduces testing properly, and this stage replaces the checks runner with JUnit then.

Checkpoint 6. Write both. Then build twice and compare the JAR's SHA-256 hashes. Are they identical? If not, why not, and how do you fix it?

Senior and architect lens

The code is small. The decisions in it aren't, and each one will be tested by a later volume. For each, here are the options, the choice, and what would make you change it.

1. A CLI is an API. People think of APIs as HTTP endpoints. A command-line tool used by scripts has exactly the same properties:

  • callers depend on its arguments, output format and exit codes;
  • changing any of them breaks callers you've never met;
  • it needs versioning (--json output gets new fields, never renamed ones) and documentation (ADR-0002).

The moment you add --json, you have a machine contract. Treat it like the HTTP contracts of Volume 3, chapter 45.

2. Functional core, imperative shell. Paise and Stats are pure: no I/O, no clock, no globals. Main does all the I/O and calls them. This is the smallest version of an idea you'll meet at every scale:

  • hexagonal architecture (Volume 3, chapter 37);
  • ports and adapters;
  • "domain logic doesn't import the framework" (Volume 13).

The payoff: stage 9 puts an HTTP server around the same Stats without changing it, and the checks test it without files.

The test of the boundary: could you call the core from a web request, a message consumer and a batch job, unchanged? If not, I/O has leaked into it.

3. Money is an integer. The options are double, BigDecimal, or integer minor units (paise). double can't represent most decimal amounts exactly (chapter 6 shows why). BigDecimal is exact, but slower and easy to misuse (equals compares scale: 1.0 isn't 1.00). Integer paise are exact and fast, and match how payment providers' APIs work. The costs:

  • you must decide rounding explicitly (step 4);
  • you must guard against overflow (Math.addExact);
  • formatting needs care (step 5).

Revisit when you support currencies with three minor-unit digits (some Middle Eastern currencies) or none (Japanese yen). The unit then becomes per-currency (Volume 23).

4. A vocabulary of exit codes, borrowed. Inventing codes (1 for this, 2 for that) means every caller must read your documentation. Borrowing sysexits.h (64 usage, 65 data error, 66 missing input) uses a vocabulary that operators may already know. The trade-off: few tools use sysexits, and many scripts only check for zero or non-zero. Keep 0 meaning exactly "all good", and you're safe either way.

5. Strict input, with a precise error per line. Rejecting 1,5 or ٣ may seem unfriendly to the person who typed them. The alternative is guessing: is 1,5 one and a half (European style) or a typo for 15? Guessing turns ambiguity into silent wrong totals. A senior engineer prefers a loud, specific rejection with a line number. Users can then fix the input, and a later stage can add a normalising importer, if the business decides it's worth it.

6. Locale belongs to people, not to protocols. The locale bug in step 5 is one of the most common production bugs in software that runs in many countries: files whose format depends on the server's locale, numbers with commas in JSON, dates parsed differently on two machines. The architectural rule: every boundary between programs uses a locale-independent format, and localisation happens only at the edge where a person reads.

7. Record decisions while they're cheap. ADR-0001 says the team records decisions; ADR-0002 is the first. In a year, "why is the exit code 65?" or "why paise?" will be asked by someone who wasn't here, maybe you. An ADR takes ten minutes now. Reconstructing the reasoning later takes hours, and sometimes the decision gets reversed by someone who never knew why it was made.

What breaks first at scale, and when you'll fix it:

Pressure What breaks Stage that addresses it
per-kitchen totals and top dishes one global total isn't enough; you need grouping stage 3 (data structures)
10 million orders a day still fine: the tool streams in constant memory. Parsing speed becomes the limit stage 4 (algorithms and measuring)
amounts from many countries INR paise assumptions Volume 23
other programs calling tbx over the network a CLI can't be called remotely stage 9 (networking), then Volume 3
orders must never be lost a CSV file isn't a durable record stage 8 (operating systems)

ADR to write for this stage: ADR-0002 (the CLI contract, from step 2), plus one line in ADR-0001 on why decisions are recorded at all.

Evidence

The stage is done when you can show all of these, with real output in your README:

  • ./build.sh passes from any working directory, and fails (non-zero exit) if you introduce a compile error, a warning, or a failing check.
  • Every exit code in ADR-0002 demonstrated with a real run: 0, 64, 65 and 66.
  • stdout carries only the result line: shown with 2>/dev/null on a file with bad lines.
  • Every rejected input from step 3 has a check, and all pass.
  • The same command gives ASCII-digit output under mr-IN, ar-EG and the default locale.
  • Two clean builds produce the same JAR hash.
  • A one-million-line input file is processed in constant memory. Generate one with a short script, run tbx on it, and note its time and the JVM's peak memory (for example with /usr/bin/time -v). You'll beat this number in stage 4.
  • ADR-0001 and ADR-0002 are committed, and the README's "Stage 1" section summarises the above.

Carry forward

What later stages will rely on, so keep these as they are or change them deliberately:

  • Paise and integer money are the money type for the whole system. Stage 2 turns them into a proper Money value type; Volume 3's services and Volume 4's database use integer minor units too.
  • The pure core (Stats) grows into the TiffinBox domain library in stage 2. Stage 9's server and Volume 3's Spring service will call it, so it must stay free of I/O.
  • The CLI contract (ADR-0002) is the first of many interface contracts. Change it only by adding, never by renaming or reusing a meaning.
  • build.sh with set -euo pipefail and -Werror is the seed of the CI pipeline in Volume 8.
  • The repository layout (tools/, docs/adr/) is where every later component goes: web/ in Volume 2, services/ in Volume 3, infra/ in Volumes 6–8.

Where Volume 1 takes TiffinBox

Each chapter of Volume 1 adds one stage. This is the plan; each stage is written in full when you reach its chapter.

Stage Chapter What TiffinBox gains The senior question it answers
1 01 Start here tbx: a strict, contract-driven CLI over orders What does a tool promise its callers?
2 02 Programming fundamentals The domain model (Money, Dish, Order, order states) with real tests, in two paradigms Which model makes illegal states unrepresentable?
3 03 Data structures A menu index, the kitchen queue, pickup-time priority and dish search Which structure, measured against the access pattern?
4 04 Algorithms Kitchen scheduling, ranking popular dishes, delivery routes on a city graph, all with complexity measured What does it cost at 100× the load?
5 05 Discrete mathematics The order lifecycle checked exhaustively, refunds, idempotency keys by hashing Can you prove it rather than test it?
6 06 Number systems A compact binary order record with a versioned format, and money edge cases How do formats evolve without breaking old data?
7 07 Computer architecture A cache-friendly layout for the day's analytics, measured Where does the time actually go in the hardware?
8 08 Operating systems A durable append-only order log with fsync, file locks and graceful shutdown What does "saved" mean when the power fails?
9 09 Networking A hand-written TCP and HTTP/1.1 server exposing the core, with timeouts What does a framework do for you, and what does it cost?
10 10 Compilers and runtimes A small language for discount rules: lexer, parser, interpreter, and conflict checks between rules When is a DSL worth it over configuration or code?
11 11 Mastery projects Release v0.1: the Volume 1 system, end to end, with its evidence Can you defend every decision from stage 1 to 10?