3 · Reliability and project · 45 MIN
Project · Inventory with checked updates
An update should either preserve invariants or fail before mutation.
Inventory operations enforce nonnegative stock and checked integer addition. Looking up a missing product returns zero for this deliberately chosen contract. Validate a requested removal before writing the new value; otherwise a rejected purchase could still corrupt stock. Assertions provide a tiny dependency-free starting point for tests, but they are disabled unless java runs with -ea. An application with persistent inventory also needs a database transaction or conditional update because this local object does not coordinate multiple processes.
Test state after failure, not only the returned boolean.
Read the example
import java.util.*;
public class Main {
static final class Inventory {
private final Map<String,Integer> stock = new HashMap<>();
int get(String id) { return stock.getOrDefault(id,0); }
void add(String id,int count) {
if (count < 0) throw new IllegalArgumentException("negative quantity");
stock.put(id,Math.addExact(get(id),count));
}
boolean buy(String id,int count) {
if (count <= 0) throw new IllegalArgumentException("positive quantity required");
int available = get(id);
if (available < count) return false;
stock.put(id,available-count); return true;
}
}
public static void main(String[] args) {
var inventory = new Inventory(); inventory.add("book",3);
assert inventory.buy("book",2);
assert !inventory.buy("book",2);
assert inventory.get("book") == 1;
System.out.println("inventory checks passed");
}
}Check the expected output
Run java -ea Main: inventory checks passed
Your challenge
Move the assertions into a repeatable test suite; add validation for blank product IDs and document concurrency limitations.
Solution cost: Expected O(1) map operations per stock update. time · Account for collection storage separately from the returned result. space
Common trap
Without -ea, assertions are skipped; never put required application work in assert expressions outside this test-only main.
Study the project implementation
import java.util.*;
public class Main {
static final class Inventory {
private final Map<String,Integer> stock = new HashMap<>();
int get(String id) { return stock.getOrDefault(id,0); }
void add(String id,int count) {
if (count < 0) throw new IllegalArgumentException("negative quantity");
stock.put(id,Math.addExact(get(id),count));
}
boolean buy(String id,int count) {
if (count <= 0) throw new IllegalArgumentException("positive quantity required");
int available = get(id);
if (available < count) return false;
stock.put(id,available-count); return true;
}
}
public static void main(String[] args) {
var inventory = new Inventory(); inventory.add("book",3);
assert inventory.buy("book",2);
assert !inventory.buy("book",2);
assert inventory.get("book") == 1;
System.out.println("inventory checks passed");
}
}Further reading: Official documentation