Part 5 of 6 · 3 min read
Safe failure
Leave things as they were, and avoid null.
Failure atomicity and missing values
EJ Item 76 asks for failure atomicity: after a method fails, the object should be in the state it had before the call. The simplest way is an immutable object, since a failed operation cannot damage an object that never changes. For mutable objects, the usual method is to validate first and change state only after every check has passed.
Here is a method that breaks the rule and a version that keeps it. The first counts the booking before the store call. If the store throws, the count is already wrong.
void bookTwo(String r2, int h) { // not failure atomic
count++;
store.save(r2.equals("bad") ? "bad" : r2 + h);
}
void bookTwoSafe(String r2, int h) { // failure atomic
String key = r2.equals("bad") ? "bad" : r2 + h;
store.save(key); // may throw
count++; // only after success
}
After a failed bookTwo, count() is 1 although nothing was saved. After a failed bookTwoSafe, count() is 0. Order the work so that the step that can fail comes before the step that changes state. Other tools: do the work on a copy and swap it in at the end, or write a recovery step that reverses the changes.
Now the missing value. CC chapter 7 advises not to return null and not to pass null, because every caller must then remember a check, and one forgotten check gives a null pointer error far from the cause. For a result that may be absent, return Optional. For a list, return an empty list.
static Optional<Booking> find(Map<String, Booking> m, String id) {
return Optional.ofNullable(m.get(id));
}
// find(Map.of(), "x").map(Booking::room).orElse("none") prints "none"
The signature tells the caller that a booking may be missing, and the caller must decide what to do. Use Optional for return values only, not for fields or parameters.
Common mistake
Catching Exception and doing nothing, or logging and carrying on as if the work succeeded. The caller then believes a booking exists when it does not.
Interview angle
Answer in your head first, then open it.
Checked or unchecked?
Checked for conditions the caller can recover from, such as a busy room. Unchecked for programming errors, such as a bad argument.
What if payment fails halfway through a booking?
Validate first, do the failing step before changing state, and give a way to undo the earlier steps. State what the caller sees.
Why not return null?
Every caller must check it, and a missed check fails far from the cause. Return an empty value or an Optional.
Check yourself:
1. What are the counts after a failed bookTwo and a failed bookTwoSafe?
2. What rule makes a method failure atomic?
3. What does find return when the id is missing?
Words you will meet
| Word | Meaning |
|---|---|
| Precondition | A rule that must hold before a method runs |
| Checked exception | An exception the compiler forces callers to handle |
| Unchecked exception | An exception that needs no declaration, for programming errors |
| Exception translation | Catching a low-level exception and throwing one fit for the layer |
| Failure atomicity | A failed call leaves the object as it was |