Skip to content

Deterministic Exports

The Course
•
25 min study

An export format is an API too. It needs stable field rules, order and newline behavior so another program—or your own importer—can read it predictably. A deterministic export produces the same text for the same logical state, regardless of insertion history.

Understand the contract

Choose a canonical order before writing text. Here IDs sort ascending, and each record occupies one line. The simplified format forbids semicolons and newline characters inside IDs or titles. Without that rule, an exported value could accidentally become two fields or two records on re-import.

StringBuilder accumulates text without creating a new String for every append. Its append calls return the builder so they can be chained, and toString produces the final text. It is mutable local working state; returning the resulting String exposes an immutable value. A builder is an implementation tool, not the public representation of your report.

For a canonical decimal field, use a validated two-place BigDecimal and toPlainString. Do not use locale-dependent currency formatting for a machine-readable field. This course's format has no quoting, escaping, currency conversion or version negotiation. Documenting those limits is more useful than calling it a universal serialization format.

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) {
        List<String> ids = new ArrayList<>(List.of("B", "A"));
        ids.sort(String::compareTo);
        StringBuilder output = new StringBuilder();
        for (String id : ids) {
            output.append(id).append(";Ready").append('\n');
        }
        System.out.print(output.toString());
    }
}
Check your prediction
Text
A;Ready
B;Ready

Trace a different case

A round-trip check compares meaningful values after export and re-import, rather than insisting the input spelling survives normalization. Padded IDs may become trimmed, and equivalent decimal spellings may become canonical two-place values. An independent expected export is still needed: a parser and exporter could share the same defect and agree with each other. As on Day 2, setScale(2) here throws if the amount has more than two places rather than rounding it.

Compare the boundary case Java
import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) {
        String raw = " A ; 2.0 ";
        String[] fields = raw.split(";", -1);
        String id = fields[0].trim();
        BigDecimal amount = new BigDecimal(fields[1].trim()).setScale(2);
        String exported = id + ";" + amount.toPlainString();
        System.out.println(exported);
        System.out.println(exported.equals(raw));
    }
}
Check your prediction
Text
A;2.00
false

Test a canonical representation independently

A canonical export must be determined by logical state, not accidental insertion history. Create two equivalent stores with different insertion orders and compare their exported text. Then check a fixed expected string to ensure both are not sharing the same ordering mistake.

Decide whether the final record ends with a newline and what empty state produces. Exact string assertions protect those rules more clearly than visual inspection of an output panel. Validate delimiters in values before export so one stored value cannot become another field or line.

A round trip checks that exported values can be reconstructed. It does not require retaining irrelevant padding or an alternative decimal spelling. Compare meaningful normalized data and the documented canonical text, rather than pretending every accepted input must be reproduced character for character.

Debug a plausible mistake

Sorting is necessary but not sufficient. A sort is canonical only if its comparator never calls two different keys equal; when it does, the tied keys keep whatever order they arrived in, and insertion history leaks back into the file.

Exercise

Repair the tied sort

IDs are case-sensitive in this format: a1 and A1 are different records. Both maps below hold the same three mappings, inserted in different orders, so their exports must be identical and the program must end with Same export: true. Predict what it prints now. The export already sorts; find out why that is not enough. The supplied version compiles; its behavior is the problem.

Debugging workspace Java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, String> first = new LinkedHashMap<>();
        first.put("a1", "Read");
        first.put("A1", "Test");
        first.put("B2", "Ship");
        Map<String, String> second = new LinkedHashMap<>();
        second.put("B2", "Ship");
        second.put("A1", "Test");
        second.put("a1", "Read");

        System.out.print(export(first));
        System.out.println("Same export: " + export(first).equals(export(second)));
    }

    static String export(Map<String, String> entries) {
        List<String> ids = new ArrayList<>(entries.keySet());
        ids.sort(String.CASE_INSENSITIVE_ORDER);
        StringBuilder output = new StringBuilder();
        for (String id : ids) {
            output.append(id).append(';').append(entries.get(id)).append('\n');
        }
        return output.toString();
    }
}
Hint 1: the idea

Ask the comparator what it thinks of a1 versus A1. If it answers "equal", the sort has no reason to reorder them, so each map keeps its own history.

Hint 2: a first step

Choose an ordering in which no two distinct IDs compare as equal. For Strings, the natural order compares characters exactly.

Show one solution
Java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, String> first = new LinkedHashMap<>();
        first.put("a1", "Read");
        first.put("A1", "Test");
        first.put("B2", "Ship");
        Map<String, String> second = new LinkedHashMap<>();
        second.put("B2", "Ship");
        second.put("A1", "Test");
        second.put("a1", "Read");

        System.out.print(export(first));
        System.out.println("Same export: " + export(first).equals(export(second)));
    }

    static String export(Map<String, String> entries) {
        List<String> ids = new ArrayList<>(entries.keySet());
        ids.sort(String::compareTo);
        StringBuilder output = new StringBuilder();
        for (String id : ids) {
            output.append(id).append(';').append(entries.get(id)).append('\n');
        }
        return output.toString();
    }
}

Expected output after repair:

Text
A1;Test
B2;Ship
a1;Read
Same export: true

CASE_INSENSITIVE_ORDER reports a1 and A1 as equal, and List.sort is stable, so the tie kept each map's insertion order: the first export started with a1, the second with A1. String::compareTo orders by character code, so uppercase letters come before lowercase and every distinct ID has exactly one position. Pick the comparator from the format's equality rule: if IDs are case-sensitive, the order must be too.

Build it yourself

Exercise

Deterministic Exports: practice

Write exportTotals(Map<String, BigDecimal> totals) for nonnull IDs with no semicolons or newlines and amounts with at most two decimal places. Return one id;amount line per entry, IDs ascending, each amount as a two-place plain string, with a newline after every line and an empty string for an empty map.

Then prove the export depends only on the logical state. Build two maps with the same totals inserted in opposite orders: the first holds B as 10 and A as 2.5, the second A as 2.50 and B as 10.00. Throw an AssertionError unless both exports are equal and an empty map exports "", then print the first export with print. The output should be:

Text
A;2.50
B;10.00
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

Two sources of difference have to disappear: the order the entries were inserted, and the way each amount was spelled. Each needs its own canonical rule before any text is built.

Hint 2: a first step

Write the export for the first map alone and print it. If the lines come out in insertion order, or an amount prints as 2.5, you know which rule is still missing. Only then add the second map and the equality check.

Show one solution
Java
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, BigDecimal> first = new LinkedHashMap<>();
        first.put("B", new BigDecimal("10"));
        first.put("A", new BigDecimal("2.5"));
        Map<String, BigDecimal> second = new LinkedHashMap<>();
        second.put("A", new BigDecimal("2.50"));
        second.put("B", new BigDecimal("10.00"));

        String exported = exportTotals(first);
        if (!exported.equals(exportTotals(second)) || !exportTotals(Map.of()).isEmpty()) {
            throw new AssertionError("export contract");
        }
        System.out.print(exported);
    }

    static String exportTotals(Map<String, BigDecimal> totals) {
        List<String> ids = new ArrayList<>(totals.keySet());
        ids.sort(String::compareTo);
        StringBuilder result = new StringBuilder();
        for (String id : ids) {
            String amount = totals.get(id).setScale(2).toPlainString();
            result.append(id).append(';').append(amount).append('\n');
        }
        return result.toString();
    }
}

Expected output:

Text
A;2.50
B;10.00

Sorting the IDs removes insertion history, and setScale(2) gives every amount the same spelling. Without a rounding mode, setScale(2) throws ArithmeticException if an amount has more than two places, which is the contract's precondition enforced rather than silently rounded. The two maps themselves are not equal: BigDecimal.equals compares scale too, so 2.5 and 2.50 differ. The export is where the canonical form is decided, and the equality check proves it.

Change it and test again

Add an exact string assertion for "A;2.50\nB;10.00\n" so an extra blank line cannot pass unnoticed. Print first.equals(second) and explain the result. Then put 2.555 in one map and see what setScale(2) does. Finally, imagine allowing newline characters inside IDs: explain why validation or a real escaping format must change before that input can be supported safely.

Explain before moving on

Which parts of the export are presentation choices and which are compatibility promises? Why is iteration over an unspecified-order map a poor foundation for a canonical export? Explain what round-trip testing proves and what an independent expected string adds.

Was this article helpful?

Your response is saved on this device.