Skip to content

On Your Own: Inventory

The Course
•
30 min study

Transfer the ideas to a different domain: an inventory batch editor. A product has an ID and a nonnegative integer stock. A command adjusts stock by a signed amount. The entire batch must either succeed or leave all products unchanged. Start from the brief rather than copying the ledger.

Understand the contract

The core accepts an existing map of product IDs to stocks and a list of adjustments. Inputs and IDs are nonnull, current stocks are nonnegative, and every adjusted ID must already exist. Process adjustments in order on a private candidate. Reject if any step would make stock negative. Repeated IDs in the batch represent successive adjustments, not retries, so they must all contribute.

Arithmetic has a boundary too. Math.addExact(int, int) returns an int sum or throws ArithmeticException on overflow, unlike ordinary int addition which wraps. Translate that exception to the same rejected-update category if your public contract uses IllegalArgumentException. Do not claim an overflowed negative number proves a legitimate out-of-stock condition.

The accepted result is a new map; the old map remains unchanged. This exercise is single-threaded and has no persistent request IDs, so it does not offer replay protection. Different domains have different identity rules: do not copy the ledger's retry behavior merely because it is available.

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.LinkedHashMap;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> stock = new LinkedHashMap<>();
        stock.put("A", 5);
        Map<String, Integer> candidate = new LinkedHashMap<>(stock);
        candidate.put("A", Math.addExact(candidate.get("A"), -2));
        System.out.println(stock.get("A"));
        System.out.println(candidate.get("A"));
    }
}
Check your prediction
Text
5
3

Trace a different case

Integer.MAX_VALUE is the largest int. Adding one with addExact reports arithmetic overflow explicitly; it does not silently turn the value negative. The exact failure category lets you distinguish a representation limit from a valid subtraction. For this independent project both become a rejected batch, but the reason should remain useful.

Compare the boundary case Java
public class Main {
    public static void main(String[] args) {
        try {
            Math.addExact(Integer.MAX_VALUE, 1);
        } catch (ArithmeticException expected) {
            System.out.println("Overflow rejected");
        }
        System.out.println(Math.addExact(5, -5));
    }
}
Check your prediction
Text
Overflow rejected
0

Build it yourself

Exercise

On Your Own: Inventory: practice

Implement record Adjustment(id,delta) and apply(Map<String,Integer>, List<Adjustment>). Return a new LinkedHashMap on success; reject unknown IDs, negative intermediate stock or overflow. Check A=5 with -2 then +1 becomes 4. Check -2 then -9 rejects while original A remains 5. Add empty-batch, exact-zero, unknown-ID and overflow tests. Print Inventory checks passed. Spend your first 20 minutes without the solution.

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

Each adjustment must see the candidate left by earlier adjustments in this batch.

Hint 2: a first step

Copy first, look up the current candidate stock, calculate with addExact, validate, then put.

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

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> current = new LinkedHashMap<>();
        current.put("A", 5);
        check("ordered adjustments", apply(current, List.of(new Adjustment("A", -2), new Adjustment("A", 1))).get("A") == 4);
        check("source unchanged", current.get("A") == 5);
        check("empty", apply(current, List.of()).equals(current));
        check("zero accepted", apply(current, List.of(new Adjustment("A", -5))).get("A") == 0);
        reject(current, List.of(new Adjustment("A", -2), new Adjustment("A", -9)));
        reject(current, List.of(new Adjustment("missing", 1)));
        reject(Map.of("A", Integer.MAX_VALUE), List.of(new Adjustment("A", 1)));
        check("late rejection unchanged", current.get("A") == 5);
        System.out.println("Inventory checks passed");
    }

    static Map<String, Integer> apply(Map<String, Integer> current, List<Adjustment> batch) {
        Map<String, Integer> candidate = new LinkedHashMap<>(current);
        for (Adjustment adjustment : batch) {
            Integer old = candidate.get(adjustment.id());
            if (old == null) {
                throw new IllegalArgumentException("unknown id");
            }
            int next;
            try {
                next = Math.addExact(old, adjustment.delta());
            } catch (ArithmeticException error) {
                throw new IllegalArgumentException("stock overflow", error);
            }
            if (next < 0) {
                throw new IllegalArgumentException("insufficient stock");
            }
            candidate.put(adjustment.id(), next);
        }
        return candidate;
    }

    static void reject(Map<String, Integer> current, List<Adjustment> batch) {
        Map<String, Integer> before = new LinkedHashMap<>(current);
        try {
            apply(current, batch);
            throw new AssertionError("invalid batch accepted");
        } catch (IllegalArgumentException expected) {
            check("rejection preserves state", current.equals(before));
        }
    }

    static void check(String name, boolean condition) {
        if (!condition) {
            throw new AssertionError(name);
        }
    }
}

record Adjustment(String id, int delta) {}

Expected output:

Text
Inventory checks passed

Every adjustment is applied to a candidate copy in order, so -2 then +1 is checked step by step and an intermediate negative stock is caught even if the batch would end positive. Math.addExact turns overflow into an exception, and that is converted into the same IllegalArgumentException category as the other rejections. The reject helper compares the source with a snapshot, so every rejection test also proves nothing leaked.

Change it and test again

After the core passes, choose one extension: typed outcomes with a command index, a canonical export, or a version-checked commit in a sequential owner class. Write its acceptance cases before implementation. Keep every existing test and show it still catches an aliased candidate defect.

Explain before moving on

Which ideas transferred from the ledger, and which rules changed? Explain why summing every delta first could violate this brief's intermediate nonnegative-stock rule even if the final total is nonnegative. Save one test that made you revise your first design.

Was this article helpful?

Your response is saved on this device.