Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -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);
}
}
Original file line number Diff line number Diff line change
@@ -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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand All @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
* <p>A failing listener does not stop the others: its exception goes to the error handler.
* <p>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<E> {

Expand All @@ -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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -15,20 +19,20 @@ 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");
}

@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();
Expand All @@ -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<String> charged = new ArrayList<>();
final List<String> 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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,21 @@ void oneFailingListenerDoesNotStopTheOthers() {
assertThat(shippedOrders).containsExactly("o-7");
assertThat(errors).containsExactly("mail server down");
}

@Test
void aFailingErrorHandlerDoesNotStopTheOthersEither() {
EventBus<OrderEvent> strictBus = new EventBus<>((event, error) -> {
throw new IllegalStateException("log sink down");
});
List<OrderEvent> 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));
}
}
Loading