Video in progress
What is an anti-corruption layer, and when do you build one when integrating with an external system?
It is a layer that translates the model of an external or legacy system into your own domain. It stops the external API's names, codes and odd rules from leaking into domain code, and if the external system changes, only this layer changes.
📖 Answer
The situation: a bank payment gateway returns a response like this:
{ "rc": "05", "st": 2, "amt": 150000, "trn_ref": "A9F...", "ext": { "hold": "Y" } }
If this DTO spreads across the services, lines like if ("05".equals(resp.getRc()) && resp.getSt() == 2) appear in the code, and whether amt is in tiyin or som is a guess everywhere.
With an ACL:
// the domain language
public sealed interface ChargeResult permits Approved, Declined, OnHold {}
public record Approved(PaymentRef ref, Money amount) implements ChargeResult {}
public record Declined(DeclineReason reason) implements ChargeResult {}
public record OnHold(PaymentRef ref) implements ChargeResult {}
// the adapter: the one place where the external model stays
class BankGatewayAdapter implements PaymentGateway {
public ChargeResult charge(ChargeCommand cmd) {
BankResponse r = client.post(toBankRequest(cmd));
if ("Y".equals(r.ext().hold())) return new OnHold(new PaymentRef(r.trnRef()));
return switch (r.rc()) {
case "00" -> new Approved(new PaymentRef(r.trnRef()), Money.ofTiyin(r.amt()));
case "05", "51" -> new Declined(DeclineReason.INSUFFICIENT_FUNDS);
default -> new Declined(DeclineReason.UNKNOWN);
};
}
}
When I build one:
- the external model is poor quality or very different from your domain;
- you might switch providers (several banks);
- you are replacing a legacy system step by step (strangler), and the new code shouldn't see the old model.
When it is overkill: if the external API is nearly the same as yours, clean and stable (for example, another service of your own with a good contract), plain mapping is enough.
Testing the ACL: keep samples of real responses in files and test the adapter against them. When news arrives that "the bank added a new code", exactly these tests and the log of the default branch help.
Sign up to mark studied questions and save your progress.