We are going to design an anti-corruption layer (ACL) that translates legacy SOAP objects to modern domain models.
The goal is to preserve invariants (business rules) during the translation.
Steps:
- Identify the legacy SOAP objects (from WSDL or existing code) and the modern domain models.
- Create a translator (or adapter) that converts the SOAP objects to domain models and vice versa (if needed).
- Ensure that the translation preserves the invariants of the domain model. This might involve:
- Validation of the SOAP data before mapping.
- Enrichment or normalization of data.
- Handling of missing or incorrect data in a way that does not break invariants (possibly by throwing exceptions or using defaults that are safe).
- The ACL should be a separate layer, so that the rest of the system only depends on the domain models.
Example scenario:
Legacy SOAP service returns a CustomerSOAP object with fields: id, name, email, status (string: "Active", "Inactive", "Pending").
Domain model Customer has: id, name, email, isActive (boolean), and an invariant that email must be valid and if the customer is active then email must not be null.
Translation:
- Convert status to isActive (if status is "Active" then true, else false).
- Validate email: if the email is invalid and the customer is active (in SOAP status "Active") then we cannot create the domain object because it violates invariant. We might throw an exception or log and set to inactive? But note: invariant says active must have email, so if we set to inactive we are changing the meaning?
We must decide on the business rule:
- If the legacy system has an invalid email but the status is "Active", then in the domain model we cannot have an active customer without a valid email. So we have two options:
a) Reject the translation (throw an exception) and let the caller handle it (maybe mark as inactive in the legacy system? but that's out of scope for ACL).
b) Adjust the translation: if the email is invalid and the status is "Active", then set isActive to false and maybe log a warning? But that might change the business meaning.
Since the ACL's job is to preserve invariants, we should not violate them. So if the incoming data does not meet the invariant, we should not create an invalid domain object. We can either:
- Fail fast (throw an exception) and let the caller decide.
- Or, if there is a known safe transformation (like converting invalid email to null and then setting isActive to false) that does not violate the invariant, we can do that.
But note: the invariant says "if isActive then email != null". So if we set isActive to false, then the email can be null (if we also set it to null) and the invariant holds. However, we are changing the active status. Is that acceptable?
We need to clarify with domain experts. In this example, let's assume that the business rule is:
"A customer must have a valid email to be active."
So if the legacy system says active and the email is invalid, then the domain model should represent that the customer is not active? Or should we consider it an error?
Since we are translating from a legacy system that might have different rules, we must decide on the translation policy.
Let's define:
- If the legacy status is "Active" and the email is invalid -> we set isActive to false and set email to null (or the invalid string? but then invariant fails if we keep invalid string and set active false? note: invariant only restricts when active, so if inactive, email can be anything? but we want to preserve invariants, so we might also want to clean the email?).
Actually, the invariant only says: if active then email must be valid and not null. It doesn't say anything about inactive. So for inactive, we can have an invalid email? Maybe in the domain model we want to store the email as provided? But then we might have an invalid email in the database for an inactive customer. That might be acceptable if the business doesn't care about inactive customers' emails.
However, the domain model might have other invariants or the email field might have a format constraint (like a regex). So we must consider the entire domain model.
Let's assume the domain model Customer has:
id: non-null, positive.
name: non-null, non-empty.
email: can be null if inactive, but if non-null must be a valid email address.
Then the translation rules could be:
Rule 1: id, name: copy if present and valid, else throw.
Rule 2: email:
if legacy status is "Active":
if email is valid -> set email and isActive=true.
else -> set email=null and isActive=false (and maybe log a warning that we are deactivating due to invalid email).
if legacy status is not "Active":
set email to the provided email (even if invalid) and isActive=false.
But note: what if the legacy status is "Inactive" and the email is valid? Then we set isActive=false and keep the valid email? That's acceptable.
Alternatively, we might want to always validate the email and if invalid, set to null regardless of status? But then for inactive, we lose the email. Maybe the business wants to keep the invalid email for inactive so they can contact the customer to update?
So we need to know the business requirements.
Since we are the engineer, we must make a decision and document it.
Let's go with:
Translation from CustomerSOAP to Customer:
- id: must be present and positive -> if not, throw.
- name: must be present and non-empty -> if not, throw.
- email:
if legacy status is "Active":
if email is valid (matches email regex) -> set email and isActive=true.
else -> set email=null and isActive=false (and log warning: "Customer {id} has invalid email but active in legacy, setting to inactive in domain").
else (legacy status is "Inactive" or "Pending"):
set email to the provided email (even if invalid) and isActive=false.
This way, we never have an active customer with an invalid email.
But note: what about "Pending"? We treat it as inactive.
Also, what if the legacy status is something else? We might default to inactive.
We can also consider having a mapping from legacy status to isActive:
"Active" -> true (if email valid) else false.
"Inactive" -> false.
"Pending" -> false.
others -> false.
And then for email, if we set isActive to true, we require valid email.
Implementation:
We'll create a Translator class with a method:
Customer translate(CustomerSOAP soap)
Steps inside:
1. Validate and map id, name (throw if invalid).
2. Determine isActive from soap.status and email validity.
3. If isActive becomes true, then we must have a valid email. If the email is invalid, we set isActive to false and email to null (and log).
4. If isActive is false, we keep the provided email (even if invalid) but note: what if the email is invalid and we set isActive to false? We keep the invalid email? Yes, because for inactive we don't have the invariant on email.
But wait: the domain model might have an invariant that email must be valid if present? That's a different invariant.
Let's assume the domain model invariant is only about active customers. So for inactive, email can be invalid.
However, the domain model might have a value object for Email that validates on creation. Then we cannot create an Email object with an invalid email. So we must adjust:
Option 1: The Email value object allows null and if non-null must be valid. Then for inactive, we can pass the invalid string? No, because the Email value object would throw on creation if invalid.
So we must decide:
If the Email value object is strict (validates on creation), then we cannot have an invalid email in the domain model at all. Then we have two options:
a) For inactive, if the email is invalid, we set the email field to null (even though we have the legacy email). But then we lose the legacy email for inactive.
b) Change the Email value object to allow invalid emails? That might not be acceptable.
Alternatively, we can have two different types:
- For active: we require a valid Email object.
- For inactive: we might have a string? But then the domain model would have a string for email? That might break the consistency.
Let's assume the domain model uses an Email value object that guarantees validity when non-null. Then:
We can only create an Email object if the string is valid. Otherwise, we must set email to null.
So the rule becomes:
If the email string is valid, create an Email object.
If invalid, set email to null (and if the status was active, we set isActive to false).
Then for inactive, we lose the invalid email. Is that acceptable?
We must ask the domain experts. But if the Email value object is designed to always hold a valid email (or null), then we cannot store an invalid email.
So the translation:
Email emailValue = null;
if (soap.email != null && isValidEmail(soap.email)) {
emailValue = new Email(soap.email);
} else {
// invalid email, so we set to null
// and if the legacy status is active, we must set isActive to false.
}
Then:
boolean isActive = false;
if (soap.status.equals("Active")) {
if (emailValue != null) {
isActive = true;
} else {
// log: legacy active but invalid email, so setting inactive.
}
} else {
isActive = false;
}
Then create Customer with:
id, name, emailValue (which might be null), isActive.
This satisfies:
- If isActive is true, then emailValue is not null (because we only set isActive=true when emailValue!=null).
- And emailValue, if not null, is a valid email (because we only create it when valid).
So the invariant holds.
But note: what if the legacy status is "Active" and the email is invalid? We set isActive=false and email=null. We are changing the active status. Is that acceptable? We are preserving the invariant, but we are changing the data.
We must document that the ACL will deactivate customers with invalid emails that are marked active in the legacy system.
Alternatively, we might want to throw an exception and let the caller decide? But then the caller would have to handle the exception and might not create the customer at all. That might be acceptable if the business requires that all active customers must have valid emails and we cannot guess.
Since the requirement is to preserve invariants, we must not create an invalid domain object. So we have two options:
Option A: Adjust the data (as above) to fit the invariant.
Option B: Fail and let the caller handle the error (by not creating the customer or by fixing the legacy data).
We'll go with Option A because it allows the system to continue and we log the discrepancy. But we must make sure the business is okay with this automatic adjustment.
Let's write the code accordingly.
However, note that the legacy system might have more status values. We should map:
"Active" -> true (only if email valid, else false)
"Inactive" -> false
"Pending" -> false
any other -> false
We can create a helper method to map status to boolean, but note that the email validity affects the active status for "Active".
So:
boolean isActiveFromLegacy(String status, String emailStr) {
if ("Active".equals(status)) {
return isValidEmail(emailStr);
} else {
return false;
}
}
But wait: what if the email is valid and status is "Active", then we set active=true. That's straightforward.
But what if the status is "Active" and email is invalid? We return false.
Then we can do:
boolean isActive = isActiveFromLegacy(soap.status, soap.email);
Email email = null;
if (isValidEmail(soap.email)) {
email = new Email(soap.email);
}
// Then create Customer with id, name, email, isActive.
But note: if the status is "Active" and email is invalid, we set isActive=false and email=null. That's fine.
However, what if the status is not "Active" and the email is valid? Then we set isActive=false and email=the valid email. That's acceptable.
But what if the status is not "Active" and the email is invalid? Then we set isActive=false and email=null. That's also acceptable.
So the above works.
But wait: what if the business rule is: for inactive, we still want to keep the email (even if invalid) for future reference? Then we cannot set it to null because we lose the data. But if the Email value object doesn't allow invalid, then we cannot store it.
So if the business wants to keep the invalid email for inactive, then we must change the domain model to allow an invalid email? Or we must store the raw email string and have a separate valid email? That's a domain model change.
Since we are only translating, we must work within the domain model.
If the domain model doesn't allow invalid email (even for inactive), then we have to drop it.
So the translation is:
Customer translate(CustomerSOAP soap) {
// Validate id and name
if (soap.id <= 0) throw new IllegalArgumentException("Invalid id");
if (soap.name == null || soap.name.isEmpty()) throw new IllegalArgumentException("Invalid name");
boolean isActive = "Active".equals(soap.status) && isValidEmail(soap.email);
Email email = null;
if (isValidEmail(soap.email)) {
email = new Email(soap.email);
}
return new Customer(soap.id, soap.name, email, isActive);
}
This is simple and satisfies the invariant: if isActive is true, then email is not null (and valid by construction).
But note: what if the legacy status is "Active" and the email is valid? Then isActive=true and email is set. Good.
What if the legacy status is "Active" and email invalid? Then isActive=false and email=null. We are deactivating the customer and clearing the email. But maybe the business wants to keep the invalid email even for inactive? We can't because the Email value object won't allow it.
If we want to keep the invalid email for inactive, then we need to change the domain model to allow a string for email? Or have a separate field for raw email? That's a bigger change.
Since the requirement is to preserve invariants, and the invariant says active customers must have valid email, we are safe.
But we are losing data for inactive customers with invalid emails. We must log that.
Alternatively, we can have a "legacyEmail" field in the domain model for storing the raw email? But that would be a violation of the domain model's purity? Maybe not, if it's only for reference.
However, the requirement says "modern domain models", so we should use the domain model as is.
Let's assume the domain model does not allow storing invalid emails at all. Then we have to drop the invalid ones.
So the above translation is acceptable.
But note: what if the legacy system has an active customer with a valid email, but the domain model has an invariant that the name must be at least 2 characters? We already validate name, but what if the domain model has more invariants? We must ensure the domain object's constructor enforces its own invariants. So we might not need to validate everything in the translator, because the domain object will throw if we try to create an invalid one.
However, it's better to validate in the translator to avoid exceptions and to log appropriately.
We should validate all the fields that the domain model requires.
Let's assume the domain model Customer has:
public Customer(Long id, String name, Email email, boolean isActive) {
if (id == null || id <= 0) throw new IllegalArgumentException("id must be positive");
if (name == null || name.trim().isEmpty()) throw new IllegalArgumentException("name is required");
if (isActive && email == null) throw new IllegalArgumentException("active customer must have email");
// Note: the Email value object already ensures validity when created, so if email is not null, it's valid.
this.id = id;
this.name = name;
this.email = email;
this.isActive = isActive;
}
Then our translator must provide:
id: positive (we check)
name: non-null and non-empty (we check)
email: if isActive is true, then email must not be null. But we set isActive only when email is valid (and then we create Email object, so not null). So we are safe.
But what if we set isActive=true and email=null? That would throw. But our logic sets isActive=true only when email is valid and then we create the Email object, so email is not null.
So we are safe.
However, what if the domain model has more invariants? We must be aware.
We can also let the domain object constructor throw and catch that in the translator? But then we lose the ability to log the specific legacy field that caused the problem.
So it's better to validate in the translator for the fields we are mapping, and then let the domain object do its own validation (which might be more complex).
But note: the domain object might have invariants that involve multiple fields. We cannot easily check those in the translator without duplicating logic. So we should let the domain object throw and then catch and wrap? But that would be an exception from the domain, which we should avoid by proper translation.
Alternatively, we can have a method in the domain model to check if a given set of values would be valid? That's not typical.
So we design the translator to produce only valid domain objects by following the mapping rules that are based on the domain invariants.
We must have a clear understanding of the domain invariants.
Since we are the engineer, we must work with domain experts to understand the invariants.
For this example, we assume we have the above.
Now, what about the reverse translation? If we need to send data back to the legacy system, we might need to translate from domain to SOAP. That would be a separate method.
CustomerSOAP toSoap(Customer customer) {
CustomerSOAP soap = new CustomerSOAP();
soap.id = customer.getId();
soap.name = customer.getName();
if (customer.getEmail() != null) {
soap.email = customer.getEmail().getValue(); // assuming Email has getValue()
} else {
soap.email = null; // or maybe empty string? depending on legacy.
}
// For status: if customer.isActive() then "Active", else "Inactive"? But what about "Pending"?
// The domain model might not have a pending state. So we map:
// active -> "Active"
// inactive -> "Inactive"
// But what if the legacy system has "Pending"? We might not be able to represent pending in the domain model?
// So we have to decide: when sending back, if the domain customer is inactive, do we send "Inactive" or "Pending"?
// We might lose information.
// We need to store the original legacy status? Maybe the domain model has a field for legacy status? That would be an anti-pattern.
// Alternatively, we can have a mapping from domain state to legacy status. Since the domain model only has active/inactive, we map:
// active -> "Active"
// inactive -> "Inactive" (or maybe "Pending" if we have a way to know? But we don't)
// So we lose the pending state. That might be acceptable if the domain model doesn't care about pending.
soap.status = customer.isActive() ? "Active" : "Inactive";
return soap;
}
This is a lossy translation. We might need to store the original legacy status in the domain model? That would be a compromise.
But the requirement is to translate legacy SOAP objects into modern domain models. The domain model should not be polluted with legacy concerns. So we should not store the legacy status.
Therefore, we must accept that when we send back, we cannot represent "Pending". We can only represent active/inactive.
If the business requires to preserve the pending state, then we must adjust the domain model to include a status field that can be "Pending", "Active", "Inactive". But then we are not really modernizing?
This is a design decision.
Let's assume the business says: in the new system, a customer is either active or inactive. The pending state from the legacy system is considered inactive in the new system. So that's acceptable.
Then the above mapping is fine.
Summary:
We design a translator that:
From SOAP to Domain:
- Validate id and name (throw if invalid).
- Determine isActive: only if legacy status is "Active" and email is valid.
- Create Email object only if the email string is valid, otherwise null.
- Create Customer with the above.
From Domain to SOAP:
- Map active -> "Active", inactive -> "Inactive".
- Email: if present, get the string value, else null.
We also need to consider:
- What about other fields? We only showed a few. We must map all required fields.
- What about data types? For example, dates, enums, etc.
- What about nested objects? We might need to recursively translate.
We can create a general framework for translation, but for simplicity we do it per type.
Let's write the code for the translator.
We'll create:
public class CustomerTranslator {
public Customer toDomain(CustomerSOAP soap) {
// validation and mapping as above
}
public CustomerSOAP toSoap(Customer customer) {
// mapping as above
}
}
But note: we might have many SOAP objects and domain models. We can create an interface for translator and have one per type.
However, for simplicity, we show one translator for Customer.
Let's code accordingly.
We assume:
CustomerSOAP (legacy) has:
Long id
String name
String email
String status // "Active", "Inactive", "Pending"
Customer (domain) has:
Long id
String name
Email email // value object, can be null
boolean isActive
And the Email value object:
public class Email {
private final String value;
public Email(String value) {
if (!isValid(value)) {
throw new IllegalArgumentException("Invalid email");
}
this.value = value;
}
public String getValue() { return value; }
// isValid method
}
We'll implement the translator with the rules above.
However, note: the legacy SOAP might have more fields. We only map the ones we need.
We must also consider that the legacy SOAP might have optional fields. We must handle nulls appropriately.
Let's code accordingly.
But wait: what if the legacy SOAP has a field that the domain model doesn't have? We ignore it.
What if the domain model has a field that the legacy SOAP doesn't have? We set it to a default (or throw if required).
In our example, the domain model has isActive, which is derived from legacy status and email. So we don't expect the legacy SOAP to have isActive.
So we are good.
Let's code.
We'll also log warnings when we adjust data (like deactivating due to invalid email).
We'll use a logger.
Code:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CustomerTranslator {
private static final Logger logger = LoggerFactory.getLogger(CustomerTranslator.class);
public Customer toDomain(CustomerSOAP soap) {
// Validate id and name
if (soap.id == null || soap.id <= 0) {
throw new IllegalArgumentException("Customer id must be positive, got: " + soap.id);
}
if (soap.name == null || soap.name.trim().isEmpty()) {
throw new IllegalArgumentException("Customer name is required");
}
// Determine if active and create Email object if valid
boolean isActive = "Active".equals(soap.status) && isValidEmail(soap.email);
Email email = null;
if (isValidEmail(soap.email)) {
email = new Email(soap.email);
} else {
// If the legacy status is Active but email is invalid, we are deactivating and clearing email.
if ("Active".equals(soap.status)) {
logger.warn("Customer {} has status Active but invalid email ({}). Setting to inactive and clearing email in domain model.",
soap.id, soap.email);
}
}
return new Customer(soap.id, soap.name, email, isActive);
}
public CustomerSOAP toSoap(Customer customer) {
CustomerSOAP soap = new CustomerSOAP();
soap.id = customer.getId();
soap.name = customer.getName();
if (customer.getEmail() != null) {
soap.email = customer.getEmail().getValue();
} else {
soap.email = null;
}
soap.status = customer.isActive() ? "Active" : "Inactive";
return soap;
}
private boolean isValidEmail(String email) {
// Simple email validation regex, adjust as needed.
if (email == null) return false;
String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
return email.matches(emailRegex);
}
}
This is a basic implementation.
However, note: what if the legacy status is null? We treat it as inactive.
We might want to be more defensive:
boolean isActive = "Active".equals(soap.status) && isValidEmail(soap.email);
If soap.status is null, then "Active".equals(soap.status) is false, so isActive=false. That's acceptable.
But what if the legacy status is "active" (lowercase)? We are doing case-sensitive. We might want to do case-insensitive?
boolean isActive = "Active".equalsIgnoreCase(soap.status) && isValidEmail(soap.email);
But then we map "active" to active. That might be acceptable.
We must know the legacy system. If it's always "Active", then we don't need to worry.
Let's assume we do case-insensitive.
Also, what about trimming the status?
boolean isActive = "Active".equalsIgnoreCase(soap.status == null ? "" : soap.status.trim()) && isValidEmail(soap.email);
But then if the status is " Active " (with spaces), we trim.
We can do:
String status = soap.status == null ? "" : soap.status.trim();
boolean isActive = "Active".equalsIgnoreCase(status) && isValidEmail(soap.email);
Similarly, for email, we might want to trim? But email can have spaces? Actually, email addresses don't have spaces, but the string might have leading/trailing spaces. We should trim the email?
if (soap.email != null) {
String trimmedEmail = soap.email.trim();
// then use trimmedEmail for validation and creating Email object.
}
But note: the Email value object might not allow spaces. So trimming is safe.
Let's adjust:
String emailStr = soap.email == null ? null : soap.email.trim();
boolean isActive = "Active".equalsIgnoreCase(status) && isValidEmail(emailStr);
Email email = null;
if (isValidEmail(emailStr)) {
email = new Email(emailStr);
}
But then we use emailStr for the Email object.
However, note: if the email is null, then emailStr is null, and isValidEmail(null) returns false, so we don't create an Email object. That's fine.
So the code becomes:
public Customer toDomain(CustomerSOAP soap) {
if (soap.id == null || soap.id <= 0) {
throw new IllegalArgumentException("Customer id must be positive, got: " + soap.id);
}
if (soap.name == null || soap.name.trim().isEmpty()) {
throw new IllegalArgumentException("Customer name is required");
}
String status = soap.status == null ? "" : soap.status.trim();
String emailStr = soap.email == null ? null : soap.email.trim();
boolean isActive = "Active".equalsIgnoreCase(status) && isValidEmail(emailStr);
Email email = null;
if (isValidEmail(emailStr)) {
email = new Email(emailStr);
} else {
if ("Active".equalsIgnoreCase(status)) {
logger.warn("Customer {} has status Active but invalid email ({}). Setting to inactive and clearing email in domain model.",
soap.id, emailStr);
}
}
return new Customer(soap.id, soap.name, email, isActive);
}
This is more robust.
Now, what about other fields? We only have id, name, email, status. If there are more, we must map them accordingly.
Also, note: the domain model might have more fields that are derived or required. We must adjust.
But the principle is the same: translate each field, and when there is a condition (like active requiring valid email) we enforce it.
We must also consider that the domain model might have aggregates and value objects. We might need to translate nested SOAP objects to nested domain objects.
Example: SOAP has an Address object, and the domain model has an Address value object. We would create an AddressTranslator.
We can have a chain of translators.
But that's beyond the scope of this example.
So, in summary:
- We design a translator per aggregate root or per value object that needs translation.
- We enforce domain invariants by adjusting the data (or throwing) during translation.
- We log when we adjust data so that we can monitor discrepancies.
This ACL ensures that the rest of the system only deals with valid domain models.
Let me know if you have any questions or if you need to handle more complex scenarios.
I'll design a comprehensive anti-corruption layer (ACL) for translating legacy SOAP services to modern domain models. This solution focuses on preserving domain invariants while handling legacy inconsistencies.
Architecture Overview
┌─────────────────┐ ┌─────────────────────┐ ┌─────────────────┐
│ Legacy SOAP │───▶│ Anti-Corruption │───▶│ Modern Domain │
│ Services │ │ Layer (ACL) │ │ Models │
└─────────────────┘ └─────────────────────┘ └─────────────────┘
│ │ │
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────────┐ ┌─────────────────┐
│ SOAP DTOs │ │ Translators/ │ │ Domain Entities │
│ (Generated) │ │ Adapters │ │ Value Objects │
└─────────────────┘ │ + Invariant Guards │ └─────────────────┘
│ + Normalization │
│ + Error Handling │
└─────────────────────┘
1. Core ACL Components
1.1 Translators (Strategy Pattern)
public interface Translator<S, D> {
D translate(S source) throws TranslationException;
boolean canTranslate(Class<S> sourceType);
}
// Base abstract translator with invariant preservation
public abstract class BaseTranslator<S, D> implements Translator<S, D> {
protected abstract void validateInvariants(D domainObject) throws InvariantViolationException;
protected abstract D createDomainObject(S source);
@Override
public final D translate(S source) throws TranslationException {
try {
// 1. Normalize legacy data
S normalized = normalize(source);
// 2. Create domain object
D domain = createDomainObject(normalized);
// 3. Validate invariants BEFORE returning
validateInvariants(domain);
// 4. Post-processing (enrichment, defaults)
return postProcess(domain);
} catch (InvariantViolationException e) {
throw new TranslationException("Invariant violation during translation", e, source);
} catch (Exception e) {
throw new TranslationException("Translation failed", e, source);
}
}
protected S normalize(S source) {
// Handle nulls, empty strings, legacy codes, format conversions
return source;
}
protected D postProcess(D domain) {
// Apply domain-specific defaults, enrich with calculated fields
return domain;
}
}
1.2 Invariant Preservation
// Domain invariants as first-class concerns
public interface Invariant<T> {
boolean test(T domainObject);
String violationMessage(T domainObject);
}
public class CompositeInvariant<T> implements Invariant<T> {
private final List<Invariant<T>> invariants = new ArrayList<>();
public CompositeInvariant<T> add(Invariant<T> invariant) {
invariants.add(invariant);
return this;
}
@Override
public boolean test(T domainObject) {
return invariants.stream()
.allMatch(inv -> inv.test(domainObject));
}
@Override
public String violationMessage(T domainObject) {
return invariants.stream()
.filter(inv -> !inv.test(domainObject))
.map(inv -> inv.violationMessage(domainObject))
.collect(Collectors.joining("; "));
}
}
// Example: Order invariants
public class OrderInvariants {
public static Invariant<Order> activeOrderMustHaveItems() {
return order -> !order.isActive() ||
order.getItems() != null &&
!order.getItems().isEmpty();
}
public static Invariant<Order> totalMatchesSumOfItems() {
return order -> {
BigDecimal sum = order.getItems().stream()
.map(item -> item.getPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
.reduce(BigDecimal.ZERO, BigDecimal::add);
return order.getTotal().compareTo(sum) == 0;
};
}
}
1.3 SOAP-Specific Adapters
// Generated SOAP DTO (from wsdl2java)
public class LegacyOrderSOAP {
private String orderId;
private String statusCode; // "A", "I", "P"
private String customerId;
private List<LegacyOrderItemSOAP> items;
private String totalAmount;
private Date orderDate;
// Getters/setters...
}
// Domain model
public class Order {
private OrderId id;
private CustomerId customerId;
private Money total;
private OrderStatus status;
private List<OrderItem> items;
private Instant createdAt;
// Business methods...
}
// Concrete translator
@Component
public class OrderTranslator extends BaseTranslator<LegacyOrderSOAP, Order> {
private final CompositeInvariant<Order> invariants;
private final MoneyAdapter moneyAdapter;
public OrderTranslator(MoneyAdapter moneyAdapter) {
this.moneyAdapter = moneyAdapter;
this.invariants = new CompositeInvariant<Order>()
.add(OrderInvariants.activeOrderMustHaveItems())
.add(OrderInvariants.totalMatchesSumOfItems());
}
@Override
protected LegacyOrderSOAP normalize(LegacyOrderSOAP source) {
// Handle legacy quirks
LegacyOrderSOAP normalized = new LegacyOrderSOAP();
normalized.setOrderId(normalizeOrderId(source.getOrderId()));
normalized.setStatusCode(
source.getStatusCode() != null ?
source.getStatusCode().trim().toUpperCase() : "I"
);
normalized.setTotalAmount(
moneyAdapter.normalizeLegacyAmount(source.getTotalAmount())
);
normalized.setItems(normalizeItems(source.getItems()));
return normalized;
}
@Override
protected Order createDomainObject(LegacyOrderSOAP source) {
OrderId orderId = new OrderId(normalizeOrderId(source.getOrderId()));
CustomerId customerId = new CustomerId(source.getCustomerId());
Money total = moneyAdapter.toDomain(source.getTotalAmount());
OrderStatus status = mapLegacyStatus(source.getStatusCode());
List<OrderItem> items = source.getItems().stream()
.map(this::translateItem)
.collect(Collectors.toList());
return new Order(orderId, customerId, total, status,
items, toInstant(source.getOrderDate()));
}
@Override
protected void validateInvariants(Order domain) throws InvariantViolationException {
if (!invariants.test(domain)) {
throw new InvariantViolationException(
"Order invariants violated: " + invariants.violationMessage(domain),
domain
);
}
}
private String normalizeOrderId(String legacyId) {
// Legacy: "ORD-2023-00123" -> Domain: "202300123"
if (legacyId == null) throw new IllegalArgumentException("OrderId cannot be null");
return legacyId.replaceAll("[^0-9]", "");
}
private OrderStatus mapLegacyStatus(String legacyStatus) {
return switch (legacyStatus) {
case "A" -> OrderStatus.ACTIVE;
case "I" -> OrderStatus.INACTIVE;
case "P" -> OrderStatus.PENDING;
default -> throw new IllegalArgumentException(
"Unknown legacy status: " + legacyStatus
);
};
}
private OrderItem translateItem(LegacyOrderItemSOAP item) {
// Similar pattern for nested objects
return new OrderItem(
new ProductId(item.getProductCode()),
item.getQuantity(),
moneyAdapter.toDomain(item.getUnitPrice())
);
}
}
2. Error Handling & Fallback Strategies
public class FallbackStrategy {
public enum Strategy {
FAIL_FAST, // Throw exception immediately
DEFAULT_VALUE, // Use safe defaults
LEGACY_PASSTHROUGH, // Keep legacy value (with warning)
AUDIT_ONLY // Log issue, use original
}
public static <T> T apply(Supplier<T> supplier,
Function<Exception, T> fallback,
Strategy strategy) {
try {
return supplier.get();
} catch (Exception e) {
switch (strategy) {
case FAIL_FAST:
throw e;
case DEFAULT_VALUE:
return fallback.apply(e);
case LEGACY_PASSTHROUGH:
// Log and return null/empty based on type
return getSafeDefault(e);
default:
throw e;
}
}
}
}
// Usage in translator:
protected Money translateAmount(String legacyAmount) {
return FallbackStrategy.apply(
() -> moneyAdapter.toDomain(legacyAmount),
ex -> Money.ZERO, // Fallback to zero
Strategy.DEFAULT_VALUE
);
}
3. Validation Pipeline
@Component
public class ValidationPipeline {
private final List<Validator<Order>> validators;
public ValidationPipeline() {
validators = List.of(
new NotNullValidator<>(),
new OrderDateNotFutureValidator(),
new CustomerExistsValidator(customerService)
);
}
public ValidationResult validate(Order order) {
List<ValidationError> errors = validators.stream()
.flatMap(v -> v.validate(order).getErrors().stream())
.collect(Collectors.toList());
return new ValidationResult(errors.isEmpty(), errors);
}
}
// Used in translator's validateInvariants:
@Override
protected void validateInvariants(Order domain) {
ValidationResult result = validationPipeline.validate(domain);
if (!result.isValid()) {
String messages = result.getErrors().stream()
.map(ValidationError::getMessage)
.collect(Collectors.joining("; "));
throw new InvariantViolationException(messages, domain);
}
}
4. Registry & Factory Pattern for Multi-Service Support
@Component
public class TranslatorRegistry {
private final Map<Class<?>, Translator<?, ?>> translators = new ConcurrentHashMap<>();
private final Map<String, String> endpointMappings;
@Autowired
public TranslatorRegistry(List<Translator<?, ?>> translatorList) {
translatorList.forEach(t -> {
Class<?> sourceType = t.getSourceType();
translators.put(sourceType, t);
});
}
@SuppressWarnings("unchecked")
public <S, D> Translator<S, D> getTranslator(Class<S> sourceType) {
Translator<S, D> translator = (Translator<S, D>) translators.get(sourceType);
if (translator == null) {
throw new IllegalArgumentException(
"No translator registered for type: " + sourceType.getSimpleName()
);
}
return translator;
}
public <S, D> D translate(String serviceName, S soapDto) {
// 1. Resolve endpoint configuration
ServiceConfig config = endpointMappings.get(serviceName);
// 2. Get appropriate translator
Translator<S, D> translator = getTranslator((Class<S>) soapDto.getClass());
// 3. Apply timeout/circuit breaker if needed
return CircuitBreaker.execute(() -> translator.translate(soapDto));
}
}
5. Monitoring & Observability
@Aspect
@Component
public class TranslatorMonitoringAspect {
private final MeterRegistry meterRegistry;
private final Counter translationErrors;
private final Timer translationDuration;
public TranslatorMonitoringAspect(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
this.translationErrors = Counter.builder("acl.translation.errors")
.description("Total translation errors")
.register(meterRegistry);
this.translationDuration = Timer.builder("acl.translation.duration")
.description("Translation duration")
.register(meterRegistry);
}
@Around("execution(* com.example.acl..*.translate(..))")
public Object monitor(ProceedingJoinPoint joinPoint) throws Throwable {
String translatorName = joinPoint.getTarget().getClass().getSimpleName();
Tags tags = Tags.of("translator", translatorName);
return translationDuration.record(() -> {
try {
return joinPoint.proceed();
} catch (TranslationException e) {
translationErrors.increment(tags);
throw e;
}
});
}
}
6. Configuration Example
acl:
translators:
- source: LegacyOrderSOAP
target: Order
strategy: STRICT # FAIL_FAST, DEFAULT_VALUE, LEGACY_PASSTHROUGH
invariants:
- "activeOrderMustHaveItems"
- "totalMatchesSumOfItems"
normalization:
trimStrings: true
emptyStringsToNull: true
dateFormat: "yyyy-MM-dd'T'HH:mm:ss"
cache:
enabled: true
ttl: 300s
circuit-breaker:
enabled: true
failureThreshold: 5
resetTimeout: 60000
monitoring:
enabled: true
logFailedTranslations: true
7. Usage Example
@Service
public class OrderService {
private final TranslatorRegistry translatorRegistry;
private final LegacySoapClient soapClient;
public Order getOrder(String orderId) {
// 1. Fetch from legacy SOAP
LegacyOrderSOAP legacyOrder = soapClient.getOrder(orderId);
// 2. Translate via ACL
try {
Order domainOrder = translatorRegistry.translate(
"orderService",
legacyOrder
);
// 3. Domain logic operates on clean model
return domainOrder.applyBusinessRules();
} catch (TranslationException e) {
// Log with context
log.error("Failed to translate order {}: {}", orderId, e.getMessage());
// Decide: fail or fallback?
throw new OrderProcessingException("Cannot process order", e);
}
}
}
8. Key Design Principles Applied
- Isolation: ACL is the ONLY component that knows about SOAP DTOs
- Invariant First: Domain invariants checked BEFORE object creation
- Fail Fast: Invalid data rejected immediately (configurable)
- Idempotent Translation: Same input → same output
- Observability: All translations monitored and logged
- Extensible: New translators via registry, not modification
- Stateless: Translators contain no business state
9. Testing Strategy
class OrderTranslatorTest {
@Test
void whenLegacyActiveWithInvalidEmail_thenDeactivatesOrder() {
// Given
LegacyOrderSOAP soap = new LegacyOrderSOAP();
soap.setStatusCode("A");
soap.setEmail("invalid-email");
soap.setTotalAmount("100.00");
// When
Order order = translator.translate(soap);
// Then
assertThat(order.getStatus()).isEqualTo(OrderStatus.INACTIVE);
assertThat(order.getEmail()).isNull();
// Invariant preserved: active orders always have email
}
@Test
void whenLegacyStatusUnknown_thenDefaultToInactive() {
// Given
LegacyOrderSOAP soap = new LegacyOrderSOAP();
soap.setStatusCode("X"); // Unknown
soap.setEmail("valid@email.com");
// When
Order order = translator.translate(soap);
// Then
assertThat(order.getStatus()).isEqualTo(OrderStatus.INACTIVE);
assertThat(order.getEmail()).isNotNull();
}
}
10. Migration Path
- Phase 1: Implement ACL with STRICT strategy (fail fast)
- Phase 2: Monitor translation failures for 2 weeks
- Phase 3: For persistent failures:
- Fix legacy data source if possible
- Add normalization rules
- Consider fallback strategies
- Phase 4: Gradually switch consumers to domain models
- Phase 5: Decommission SOAP clients after verification
Critical Considerations
- Performance: Cache translations for immutable reference data
- Error Recovery: Implement dead-letter queue for failed translations
- Schema Evolution: Handle versioned SOAP contracts via translator selection
- Security: Sanitize legacy inputs (XXE, injection attacks)
- Transactionality: Ensure ACL operations are part of larger business transactions
This ACL ensures zero leakage of legacy concerns into the domain layer while providing comprehensive observability and configurable handling of imperfect data. The invariant checks happen before domain object creation, guaranteeing that all domain objects in the system are always valid.