Skip to content

Instantly share code, notes, and snippets.

@ccjmne
Last active June 23, 2023 08:54
Show Gist options
  • Save ccjmne/7bd3003c21c29f74f07c6d793f8f437c to your computer and use it in GitHub Desktop.
Save ccjmne/7bd3003c21c29f74f07c6d793f8f437c to your computer and use it in GitHub Desktop.
Alternatives to the Autocloseable trick
// The current state:
try (BuyerDataState buyerDataState = this.notifyBuyerUpdateManager.beginAddressUpdate(buyer.getLegalEntityId())) {
return buyerHandler.updateBuyer(buyer);
}
private static class NotifyBuyerUpdateManager {
public static BuyerDataState beginAddressUpdate() {
final BuyerData currentBuyerData = loadBuyerData();
return new AutoCloseable() {
@Override
public void close() {
final newBuyerData = loadBuyerData();
if (!newBuyerData.equals(oldBuyerData)) {
notifyBuyerDataChanged();
}
}
}
}
}
// -----------------------------------------------------------------------------
// Alternative #1:
return Transaction.execute(
() -> loadBuyerData(),
(unused) -> buyerHandler.updateBuyer(buyer),
(previousBuyerData) -> {
final BuyerData newBuyerData = loadBuyerData();
if (!newBuyerData.equals(previousBuyerData)) {
notifyBuyerDataChanged();
}
}
);
private static class Transaction {
public static <Ctx, Ret> Ret execute(
final Supplier<Ctx> context,
final Function<Ctx, Ret> transaction,
final Consumer<Ctx> then
) {
final Ctx ctx = context.get();
try {
return transaction.apply(ctx);
} finally {
then.accept(ctx);
}
}
}
// -----------------------------------------------------------------------------
// Alternative #2:
final BuyerData currentBuyerData = loadBuyerData();
try {
return buyerHandler.updateBuyer(buyer);
} finally {
final BuyerData newBuyerData = loadBuyerData();
if (!newBuyerData.equals(previousBuyerData)) {
notifyBuyerDataChanged();
}
}
// -----------------------------------------------------------------------------
// Alternative #3:
final BuyerData previousBuyerData = loadBuyerData();
final Buyer result = buyerHandler.updateBuyer(buyer);
final BuyerData newBuyerData = loadBuyerData();
if (!newBuyerData.equals(previousBuyerData)) {
notifyBuyerDataChanged();
}
return result;
// -----------------------------------------------------------------------------
// Alternative #4:
final Buyer result = buyerHandler.updateBuyer(buyer);
notifyBuyerDataChanged();
return result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment