diff --git a/README.md b/README.md index f936775..22fa001 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ cd modern-java-design-patterns ./mvnw verify ``` -The build compiles with all warnings as errors and runs 78 tests, including the architecture rules. +The build compiles with all warnings as errors and runs 80 tests, including the architecture rules. ## Tests and quality diff --git a/src/main/java/com/alejandrolunatech/patterns/gof/facade/CheckoutFacade.java b/src/main/java/com/alejandrolunatech/patterns/gof/facade/CheckoutFacade.java index 79a52a2..0e9707d 100644 --- a/src/main/java/com/alejandrolunatech/patterns/gof/facade/CheckoutFacade.java +++ b/src/main/java/com/alejandrolunatech/patterns/gof/facade/CheckoutFacade.java @@ -5,6 +5,7 @@ import com.alejandrolunatech.patterns.gof.facade.Subsystems.PaymentDeclinedException; import com.alejandrolunatech.patterns.gof.facade.Subsystems.Payments; import com.alejandrolunatech.patterns.gof.facade.Subsystems.Shipping; +import com.alejandrolunatech.patterns.gof.facade.Subsystems.ShippingUnavailableException; import java.util.Objects; /** @@ -49,7 +50,14 @@ public Result placeOrder(OrderRequest request) { inventory.release(reservation); return new Result.Rejected("payment declined: " + e.getMessage()); } - String tracking = shipping.book(reservation, request.address()); + String tracking; + try { + tracking = shipping.book(reservation, request.address()); + } catch (ShippingUnavailableException e) { + payments.refund(payment); + inventory.release(reservation); + return new Result.Rejected("shipping unavailable: " + e.getMessage()); + } return new Result.Placed(payment, tracking); } } diff --git a/src/main/java/com/alejandrolunatech/patterns/gof/facade/README.md b/src/main/java/com/alejandrolunatech/patterns/gof/facade/README.md index 3fd43a1..df0cb83 100644 --- a/src/main/java/com/alejandrolunatech/patterns/gof/facade/README.md +++ b/src/main/java/com/alejandrolunatech/patterns/gof/facade/README.md @@ -1,8 +1,8 @@ # Facade -**Problem.** Placing an order touches inventory, payments and shipping, in a set order, with a compensation step when payment fails. Every caller repeating that sequence will get it wrong somewhere. +**Problem.** Placing an order touches inventory, payments and shipping, in a set order, with compensation steps when a later step fails. Every caller repeating that sequence will get it wrong somewhere. -**The code.** `CheckoutFacade.placeOrder` is the one entry point. It reserves stock, charges, books shipping, and releases the reservation if the payment is declined. The result is a sealed type: `Placed` or `Rejected`. +**The code.** `CheckoutFacade.placeOrder` is the one entry point. It reserves stock, charges and books shipping. When a step fails it undoes the ones before it, newest first: a declined payment releases the reservation, and unavailable shipping refunds the payment and then releases the reservation. The result is a sealed type: `Placed` or `Rejected`. **What modern Java changes.** A sealed result type replaces exceptions for expected outcomes, so callers must handle both cases. diff --git a/src/main/java/com/alejandrolunatech/patterns/gof/facade/Subsystems.java b/src/main/java/com/alejandrolunatech/patterns/gof/facade/Subsystems.java index 26acc5c..358353c 100644 --- a/src/main/java/com/alejandrolunatech/patterns/gof/facade/Subsystems.java +++ b/src/main/java/com/alejandrolunatech/patterns/gof/facade/Subsystems.java @@ -18,10 +18,13 @@ public interface Payments { /** Returns a payment reference, or throws {@link PaymentDeclinedException}. */ String charge(String customerId, long amountCents); + + void refund(String paymentReference); } public interface Shipping { + /** Returns a tracking code, or throws {@link ShippingUnavailableException}. */ String book(String reservationId, String address); } @@ -34,6 +37,15 @@ public OutOfStockException(String sku) { } } + public static final class ShippingUnavailableException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public ShippingUnavailableException(String reason) { + super(reason); + } + } + public static final class PaymentDeclinedException extends RuntimeException { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alejandrolunatech/patterns/gof/observer/EventBus.java b/src/main/java/com/alejandrolunatech/patterns/gof/observer/EventBus.java index 07cee12..2a19e90 100644 --- a/src/main/java/com/alejandrolunatech/patterns/gof/observer/EventBus.java +++ b/src/main/java/com/alejandrolunatech/patterns/gof/observer/EventBus.java @@ -10,7 +10,8 @@ * Observers are plain {@link Consumer}s. Subscribing returns a handle that unsubscribes, so * listeners can be used with try-with-resources and never leak. * - *

A failing listener does not stop the others: its exception goes to the error handler. + *

A failing listener does not stop the others: its exception goes to the error handler. If + * the error handler itself throws, that is dropped too, so delivery always reaches every listener. */ public final class EventBus { @@ -35,12 +36,20 @@ public int publish(E event) { listener.accept(event); delivered++; } catch (RuntimeException e) { - onListenerError.accept(event, e); + report(event, e); } } return delivered; } + private void report(E event, RuntimeException error) { + try { + onListenerError.accept(event, error); + } catch (RuntimeException handlerFailure) { + // The handler was the last place to report to; the remaining listeners matter more. + } + } + public int listenerCount() { return listeners.size(); } diff --git a/src/main/java/com/alejandrolunatech/patterns/gof/observer/README.md b/src/main/java/com/alejandrolunatech/patterns/gof/observer/README.md index 46ac7db..3289c91 100644 --- a/src/main/java/com/alejandrolunatech/patterns/gof/observer/README.md +++ b/src/main/java/com/alejandrolunatech/patterns/gof/observer/README.md @@ -2,7 +2,7 @@ **Problem.** When an order ships, several parts of the system want to know: email, analytics, the warehouse. The order code should not call each of them. -**The code.** `EventBus` keeps a list of `Consumer`s. `subscribe` returns a `Subscription` that removes the listener when closed. A listener that throws is reported to an error handler and does not stop the others. +**The code.** `EventBus` keeps a list of `Consumer`s. `subscribe` returns a `Subscription` that removes the listener when closed. A listener that throws is reported to an error handler and does not stop the others; neither does an error handler that throws. **What modern Java changes.** Listeners are lambdas instead of anonymous classes, events are records in a sealed hierarchy, and the unsubscribe handle is an `AutoCloseable`. diff --git a/src/test/java/com/alejandrolunatech/patterns/gof/facade/CheckoutFacadeTest.java b/src/test/java/com/alejandrolunatech/patterns/gof/facade/CheckoutFacadeTest.java index 7bb72dc..9697492 100644 --- a/src/test/java/com/alejandrolunatech/patterns/gof/facade/CheckoutFacadeTest.java +++ b/src/test/java/com/alejandrolunatech/patterns/gof/facade/CheckoutFacadeTest.java @@ -7,6 +7,10 @@ import com.alejandrolunatech.patterns.gof.facade.Subsystems.Inventory; import com.alejandrolunatech.patterns.gof.facade.Subsystems.OutOfStockException; import com.alejandrolunatech.patterns.gof.facade.Subsystems.PaymentDeclinedException; +import com.alejandrolunatech.patterns.gof.facade.Subsystems.Payments; +import com.alejandrolunatech.patterns.gof.facade.Subsystems.ShippingUnavailableException; +import java.util.ArrayList; +import java.util.List; import java.util.HashSet; import java.util.Set; import org.junit.jupiter.api.Test; @@ -15,10 +19,11 @@ class CheckoutFacadeTest { private final OrderRequest request = new OrderRequest("c-1", "SKU-1", 2, 4_990, "Poolsterstraat 1, Hoorn"); private final FakeInventory inventory = new FakeInventory(); + private final FakePayments payments = new FakePayments(); @Test void placesAnOrderInOneCall() { - CheckoutFacade facade = new CheckoutFacade(inventory, (customer, cents) -> "pay-1", (reservation, address) -> "3S123"); + CheckoutFacade facade = new CheckoutFacade(inventory, payments, (reservation, address) -> "3S123"); assertThat(facade.placeOrder(request)).isEqualTo(new Result.Placed("pay-1", "3S123")); assertThat(inventory.reserved).containsExactly("res-SKU-1"); @@ -26,9 +31,8 @@ void placesAnOrderInOneCall() { @Test void releasesTheReservationWhenPaymentIsDeclined() { - CheckoutFacade facade = new CheckoutFacade(inventory, (customer, cents) -> { - throw new PaymentDeclinedException("insufficient funds"); - }, (reservation, address) -> "never"); + payments.declineWith = "insufficient funds"; + CheckoutFacade facade = new CheckoutFacade(inventory, payments, (reservation, address) -> "never"); assertThat(facade.placeOrder(request)).isEqualTo(new Result.Rejected("payment declined: insufficient funds")); assertThat(inventory.reserved).isEmpty(); @@ -37,11 +41,46 @@ void releasesTheReservationWhenPaymentIsDeclined() { @Test void rejectsWithoutChargingWhenOutOfStock() { inventory.outOfStock = true; - CheckoutFacade facade = new CheckoutFacade(inventory, (customer, cents) -> { - throw new AssertionError("must not charge"); - }, (reservation, address) -> "never"); + CheckoutFacade facade = new CheckoutFacade(inventory, payments, (reservation, address) -> "never"); assertThat(facade.placeOrder(request)).isEqualTo(new Result.Rejected("out of stock: SKU-1")); + assertThat(payments.charged).isEmpty(); + } + + @Test + void refundsAndReleasesWhenShippingIsUnavailable() { + CheckoutFacade facade = new CheckoutFacade(inventory, payments, (reservation, address) -> { + throw new ShippingUnavailableException("no carrier for this address"); + }); + + assertThat(facade.placeOrder(request)) + .isEqualTo(new Result.Rejected("shipping unavailable: no carrier for this address")); + assertThat(payments.charged).isEmpty(); + assertThat(payments.refunded).containsExactly("pay-1"); + assertThat(inventory.reserved).isEmpty(); + } + + static final class FakePayments implements Payments { + + final List charged = new ArrayList<>(); + final List refunded = new ArrayList<>(); + String declineWith; + + @Override + public String charge(String customerId, long amountCents) { + if (declineWith != null) { + throw new PaymentDeclinedException(declineWith); + } + String reference = "pay-" + (charged.size() + refunded.size() + 1); + charged.add(reference); + return reference; + } + + @Override + public void refund(String paymentReference) { + charged.remove(paymentReference); + refunded.add(paymentReference); + } } static final class FakeInventory implements Inventory { diff --git a/src/test/java/com/alejandrolunatech/patterns/gof/observer/EventBusTest.java b/src/test/java/com/alejandrolunatech/patterns/gof/observer/EventBusTest.java index 29c47cd..67649ed 100644 --- a/src/test/java/com/alejandrolunatech/patterns/gof/observer/EventBusTest.java +++ b/src/test/java/com/alejandrolunatech/patterns/gof/observer/EventBusTest.java @@ -54,4 +54,21 @@ void oneFailingListenerDoesNotStopTheOthers() { assertThat(shippedOrders).containsExactly("o-7"); assertThat(errors).containsExactly("mail server down"); } + + @Test + void aFailingErrorHandlerDoesNotStopTheOthersEither() { + EventBus strictBus = new EventBus<>((event, error) -> { + throw new IllegalStateException("log sink down"); + }); + List heard = new ArrayList<>(); + strictBus.subscribe(event -> { + throw new IllegalStateException("mail server down"); + }); + strictBus.subscribe(heard::add); + + int delivered = strictBus.publish(new OrderEvent.Placed("o-8", 900)); + + assertThat(delivered).isEqualTo(1); + assertThat(heard).containsExactly(new OrderEvent.Placed("o-8", 900)); + } }