Kapitel 1 God Service zerlegen und Verantwortlichkeiten schneiden6 Simulationen
Sechs realistische Legacy-Situationen mit Sicherheitsnetz, fünf nachvollziehbaren Runs, finalem Java-Code und Architektur-SVG.
Refactoring Simulator
Sechs realistische Legacy-Situationen mit Sicherheitsnetz, fünf nachvollziehbaren Runs, finalem Java-Code und Architektur-SVG.
24 Simulationen offen.
Simulation 1 · God Order Service 5 Refactoring-Runs
Erkannte Risiken
God Class, Long Method, Primitive Obsession
Zielmuster
Strategy, Ports and Adapters
Run-Folge
- Characterization Test und Verhaltensinventar
- Verantwortlichkeiten und Fachbegriffe extrahieren
- Seiteneffekte hinter Ports verschieben
- Änderungsachse durch passendes Pattern kapseln
- Zielarchitektur, Regressionstests und Restschulden dokumentieren
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class OrderRefactoringSimulator {
private OrderRefactoringSimulator() {}
public record Money(long cents){ public Money { if(cents<0) throw new IllegalArgumentException("negative"); } }
public record Order(String customerType,List<Money> items) { public Order { items=List.copyOf(items); } }
// Design Pattern: Strategy - separates the changing discount policy.
public interface DiscountPolicy { Money apply(Order order, Money subtotal); }
// Ports and Adapters: technical side effect is behind a port.
public interface OrderAuditPort { void recorded(Order order, Money total); }
public static final class PricingService {
private final Map<String,DiscountPolicy> policies; private final OrderAuditPort audit;
public PricingService(Map<String,DiscountPolicy> policies,OrderAuditPort audit){this.policies=Map.copyOf(policies);this.audit=audit;}
public Money price(Order order){ long sum=order.items().stream().mapToLong(Money::cents).sum(); var subtotal=new Money(sum); var total=policies.getOrDefault(order.customerType(),(o,s)->s).apply(order,subtotal); audit.recorded(order,total); return total; }
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Strategy, Ports and Adapters |
| Offene Restschuld | Produktionsadapter und Lasttests bleiben umgebungsspezifisch. |
Simulation 2 · Approval Rule Engine 5 Refactoring-Runs
Erkannte Risiken
Switch Explosion, Shotgun Surgery, Hidden Policy
Zielmuster
Specification, Composite
Run-Folge
- Characterization Test und Verhaltensinventar
- Verantwortlichkeiten und Fachbegriffe extrahieren
- Seiteneffekte hinter Ports verschieben
- Änderungsachse durch passendes Pattern kapseln
- Zielarchitektur, Regressionstests und Restschulden dokumentieren
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class ApprovalRefactoringSimulator {
private ApprovalRefactoringSimulator() {}
public record Request(long amountCents, boolean verified, int riskScore){}
public record Decision(boolean approved,List<String> reasons){ public Decision { reasons=List.copyOf(reasons); } }
// Design Pattern: Specification - each business rule becomes composable and testable.
public interface Specification { Optional<String> violation(Request request); }
// Design Pattern: Composite - combines independent specifications.
public static final class ApprovalPolicy {
private final List<Specification> rules; public ApprovalPolicy(List<Specification> rules){this.rules=List.copyOf(rules);}
public Decision decide(Request request){var reasons=rules.stream().map(r->r.violation(request)).flatMap(Optional::stream).toList();return new Decision(reasons.isEmpty(),reasons);}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Specification, Composite |
| Offene Restschuld | Produktionsadapter und Lasttests bleiben umgebungsspezifisch. |
Simulation 3 · Batch Import Pipeline 5 Refactoring-Runs
Erkannte Risiken
Mixed Abstraction, Error Swallowing, Resource Leak
Zielmuster
Pipeline, Result Type
Run-Folge
- Characterization Test und Verhaltensinventar
- Verantwortlichkeiten und Fachbegriffe extrahieren
- Seiteneffekte hinter Ports verschieben
- Änderungsachse durch passendes Pattern kapseln
- Zielarchitektur, Regressionstests und Restschulden dokumentieren
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class ImportRefactoringSimulator {
private ImportRefactoringSimulator() {}
public sealed interface ImportResult permits Imported,Rejected {}
public record Imported(String id) implements ImportResult {} public record Rejected(String reason) implements ImportResult {}
@FunctionalInterface public interface Stage { ImportResult execute(String input); }
// Enterprise Pattern: Pipeline - explicit ordered stages replace one mixed method.
public static final class ImportPipeline {
private final List<Stage> stages; public ImportPipeline(List<Stage> stages){this.stages=List.copyOf(stages);}
public ImportResult run(String input){ImportResult current=new Imported(input); for(var stage:stages){current=stage.execute(current instanceof Imported i?i.id():input); if(current instanceof Rejected) return current;} return current;}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Pipeline, Result Type |
| Offene Restschuld | Produktionsadapter und Lasttests bleiben umgebungsspezifisch. |
Simulation 4 · Notification Hub 5 Refactoring-Runs
Erkannte Risiken
Conditional Dispatch, Tight Coupling, Duplicate Retry
Zielmuster
Adapter, Registry, Decorator
Run-Folge
- Characterization Test und Verhaltensinventar
- Verantwortlichkeiten und Fachbegriffe extrahieren
- Seiteneffekte hinter Ports verschieben
- Änderungsachse durch passendes Pattern kapseln
- Zielarchitektur, Regressionstests und Restschulden dokumentieren
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class NotificationRefactoringSimulator {
private NotificationRefactoringSimulator() {}
public record Message(String channel,String recipient,String body){}
// Ports and Adapters: providers implement the stable outbound port.
public interface NotificationPort { void send(Message message); }
// Pattern: Registry - resolves adapters without conditional dispatch.
public static final class NotificationRegistry { private final Map<String,NotificationPort> ports; public NotificationRegistry(Map<String,NotificationPort> ports){this.ports=Map.copyOf(ports);} public NotificationPort resolve(String channel){var p=ports.get(channel);if(p==null)throw new IllegalArgumentException(channel);return p;} }
// Pattern: Decorator - adds retry without changing provider adapters.
public record RetryingNotificationPort(NotificationPort delegate,int attempts) implements NotificationPort { public void send(Message message){RuntimeException last=null;for(int i=0;i<attempts;i++){try{delegate.send(message);return;}catch(RuntimeException ex){last=ex;}}throw last;} }
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Adapter, Registry, Decorator |
| Offene Restschuld | Produktionsadapter und Lasttests bleiben umgebungsspezifisch. |
Simulation 5 · Inventory Reservation 5 Refactoring-Runs
Erkannte Risiken
Check-then-act Race, Shared Mutable State
Zielmuster
Repository, Atomic Operation
Run-Folge
- Characterization Test und Verhaltensinventar
- Verantwortlichkeiten und Fachbegriffe extrahieren
- Seiteneffekte hinter Ports verschieben
- Änderungsachse durch passendes Pattern kapseln
- Zielarchitektur, Regressionstests und Restschulden dokumentieren
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.concurrent.*;
public final class InventoryRefactoringSimulator {
private InventoryRefactoringSimulator() {}
public sealed interface ReservationResult permits Reserved,Insufficient {}
public record Reserved(String sku,int remaining) implements ReservationResult{} public record Insufficient(String sku,int available) implements ReservationResult{}
// Repository Pattern: exposes one atomic domain operation, not get-then-set.
public interface InventoryRepository { ReservationResult reserve(String sku,int quantity); }
public static final class InMemoryInventoryRepository implements InventoryRepository {
private final ConcurrentHashMap<String,Integer> stock=new ConcurrentHashMap<>(); public void put(String sku,int qty){stock.put(sku,qty);}
public ReservationResult reserve(String sku,int qty){final ReservationResult[] out=new ReservationResult[1];stock.compute(sku,(k,current)->{int available=current==null?0:current;if(available<qty){out[0]=new Insufficient(sku,available);return available;}int left=available-qty;out[0]=new Reserved(sku,left);return left;});return out[0];}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Repository, Atomic Operation |
| Offene Restschuld | Produktionsadapter und Lasttests bleiben umgebungsspezifisch. |
Simulation 6 · Customer Merge Workflow 5 Refactoring-Runs
Erkannte Risiken
Boolean Blindness, Temporal Coupling, Partial Updates
Zielmuster
Command, Unit of Work, Domain Event
Run-Folge
- Characterization Test und Verhaltensinventar
- Verantwortlichkeiten und Fachbegriffe extrahieren
- Seiteneffekte hinter Ports verschieben
- Änderungsachse durch passendes Pattern kapseln
- Zielarchitektur, Regressionstests und Restschulden dokumentieren
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class CustomerMergeRefactoringSimulator {
private CustomerMergeRefactoringSimulator() {}
public record Customer(String id,String email,boolean active){}
// Command Pattern: captures the complete use-case input.
public record MergeCustomers(String survivorId,String duplicateId){}
public interface CustomerRepository { Optional<Customer> find(String id); void save(Customer customer); void delete(String id); }
// Unit of Work: defines the atomic boundary for multiple repository changes.
public interface UnitOfWork { void inTransaction(Runnable work); }
public interface DomainEventPublisher { void publish(CustomerMerged event); }
public record CustomerMerged(String survivorId,String duplicateId){}
public record MergeHandler(CustomerRepository repository,UnitOfWork unitOfWork,DomainEventPublisher events){ public void handle(MergeCustomers command){unitOfWork.inTransaction(()->{var survivor=repository.find(command.survivorId()).orElseThrow();var duplicate=repository.find(command.duplicateId()).orElseThrow();repository.save(new Customer(survivor.id(),survivor.email().isBlank()?duplicate.email():survivor.email(),survivor.active()||duplicate.active()));repository.delete(duplicate.id());events.publish(new CustomerMerged(survivor.id(),duplicate.id()));});} }
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Command, Unit of Work, Domain Event |
| Offene Restschuld | Produktionsadapter und Lasttests bleiben umgebungsspezifisch. |
Kapitel 2 Subscriptions, Zeitregeln und wiederholbare Abläufe6 Simulationen
Sechs weitere Enterprise-Simulationen mit Sicherheitsnetz, fünf nachvollziehbaren Runs, finalem Java-21-Code und themenspezifischer Architektur-SVG.
Refactoring Simulator
Sechs weitere Enterprise-Simulationen mit Sicherheitsnetz, fünf nachvollziehbaren Runs, finalem Java-21-Code und themenspezifischer Architektur-SVG.
6 Simulationen offen.
Simulation 7 · Subscription Renewal 5 Refactoring-Runs
Erkannte Risiken
Temporal Coupling, Hidden Clock, Mixed Billing
Zielmuster
Clock Port, Policy, Command
Run-Folge
- Characterization Tests und Verhaltensinventar
- Fachbegriffe und Verantwortlichkeiten extrahieren
- Seiteneffekte hinter Ports verschieben
- Änderungsachse mit Pattern kapseln
- Regressionstests, Architekturgrenzen und Restschulden dokumentieren
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.time.*;
public final class RenewalRefactoringSimulator {
private RenewalRefactoringSimulator() {}
public record Subscription(String id, LocalDate validUntil, boolean paused) {}
public record RenewalDecision(boolean renew, String reason) {}
// Design Pattern: Policy - isolates business eligibility from orchestration.
public interface RenewalPolicy { RenewalDecision decide(Subscription subscription, LocalDate today); }
// Ports and Adapters: time becomes deterministic and testable.
public interface ClockPort { LocalDate today(); }
// Command Pattern: explicit use-case input replaces temporal coupling.
public record RenewSubscription(String subscriptionId) {}
public record RenewalService(RenewalPolicy policy, ClockPort clock) {
public RenewalDecision evaluate(Subscription subscription) { return policy.decide(subscription, clock.today()); }
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Clock Port, Policy, Command |
| Offene Restschuld | Produktionsadapter, Persistenz- und Lasttests bleiben umgebungsspezifisch. |
Simulation 8 · Fraud Case Triage 5 Refactoring-Runs
Erkannte Risiken
Rule Spaghetti, Priority Leakage, Boolean Blindness
Zielmuster
Specification, Chain of Responsibility
Run-Folge
- Characterization Tests und Verhaltensinventar
- Fachbegriffe und Verantwortlichkeiten extrahieren
- Seiteneffekte hinter Ports verschieben
- Änderungsachse mit Pattern kapseln
- Regressionstests, Architekturgrenzen und Restschulden dokumentieren
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class FraudTriageRefactoringSimulator {
private FraudTriageRefactoringSimulator() {}
public record Case(long amountCents, int riskScore, boolean trustedDevice) {}
public record Triage(String queue, List<String> reasons) { public Triage { reasons=List.copyOf(reasons); } }
// Design Pattern: Specification - each signal is independently testable.
public interface Rule { Optional<String> violation(Case fraudCase); }
// Design Pattern: Chain of Responsibility - ordered routing replaces nested conditionals.
public static final class TriageChain {
private final List<Rule> rules; public TriageChain(List<Rule> rules){this.rules=List.copyOf(rules);}
public Triage route(Case c){var reasons=rules.stream().map(r->r.violation(c)).flatMap(Optional::stream).toList();return new Triage(reasons.isEmpty()?"AUTO":"MANUAL",reasons);}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Specification, Chain of Responsibility |
| Offene Restschuld | Produktionsadapter, Persistenz- und Lasttests bleiben umgebungsspezifisch. |
Simulation 9 · Invoice Reconciliation 5 Refactoring-Runs
Erkannte Risiken
N+1 Reads, Partial Updates, Duplicate Matching
Zielmuster
Batch Repository, Unit of Work
Run-Folge
- Characterization Tests und Verhaltensinventar
- Fachbegriffe und Verantwortlichkeiten extrahieren
- Seiteneffekte hinter Ports verschieben
- Änderungsachse mit Pattern kapseln
- Regressionstests, Architekturgrenzen und Restschulden dokumentieren
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class InvoiceReconciliationRefactoringSimulator {
private InvoiceReconciliationRefactoringSimulator() {}
public record Invoice(String id,long amountCents){} public record Payment(String reference,long amountCents){}
// Repository Pattern: exposes batch retrieval instead of N+1 lookups.
public interface ReconciliationRepository { Map<String,Invoice> invoicesById(Set<String> ids); void markMatched(Set<String> ids); }
// Unit of Work: matching and state transition share one atomic boundary.
public interface UnitOfWork { void inTransaction(Runnable work); }
public record ReconciliationService(ReconciliationRepository repository, UnitOfWork unitOfWork){
public Set<String> reconcile(List<Payment> payments){var ids=payments.stream().map(Payment::reference).collect(java.util.stream.Collectors.toSet());var invoices=repository.invoicesById(ids);var matched=new HashSet<String>();for(var p:payments){var i=invoices.get(p.reference());if(i!=null&&i.amountCents()==p.amountCents())matched.add(i.id());}unitOfWork.inTransaction(()->repository.markMatched(Set.copyOf(matched)));return Set.copyOf(matched);}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Batch Repository, Unit of Work |
| Offene Restschuld | Produktionsadapter, Persistenz- und Lasttests bleiben umgebungsspezifisch. |
Simulation 10 · Shipment Routing 5 Refactoring-Runs
Erkannte Risiken
Switch Explosion, Provider Leakage, Hard-coded Fallback
Zielmuster
Strategy Registry, Adapter
Run-Folge
- Characterization Tests und Verhaltensinventar
- Fachbegriffe und Verantwortlichkeiten extrahieren
- Seiteneffekte hinter Ports verschieben
- Änderungsachse mit Pattern kapseln
- Regressionstests, Architekturgrenzen und Restschulden dokumentieren
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class ShipmentRoutingRefactoringSimulator {
private ShipmentRoutingRefactoringSimulator() {}
public record Shipment(String destination,int weightGrams){} public record Route(String provider,String service){}
// Design Pattern: Strategy - each routing policy owns one change axis.
public interface RoutingStrategy { boolean supports(Shipment shipment); Route route(Shipment shipment); }
// Pattern: Registry - selection replaces provider switch statements.
public static final class RoutingRegistry { private final List<RoutingStrategy> strategies; public RoutingRegistry(List<RoutingStrategy> strategies){this.strategies=List.copyOf(strategies);} public Route resolve(Shipment s){return strategies.stream().filter(x->x.supports(s)).findFirst().orElseThrow().route(s);} }
// Adapter Pattern: carrier-specific APIs remain outside the domain-facing strategy.
public interface CarrierAdapter { String book(Route route, Shipment shipment); }
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Strategy Registry, Adapter |
| Offene Restschuld | Produktionsadapter, Persistenz- und Lasttests bleiben umgebungsspezifisch. |
Simulation 11 · Access Provisioning 5 Refactoring-Runs
Erkannte Risiken
Implicit Workflow, Compensating Actions Missing, Shared Flags
Zielmuster
Process Manager, Command
Run-Folge
- Characterization Tests und Verhaltensinventar
- Fachbegriffe und Verantwortlichkeiten extrahieren
- Seiteneffekte hinter Ports verschieben
- Änderungsachse mit Pattern kapseln
- Regressionstests, Architekturgrenzen und Restschulden dokumentieren
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class AccessProvisioningRefactoringSimulator {
private AccessProvisioningRefactoringSimulator() {}
public record ProvisionAccess(String userId, Set<String> roles){ public ProvisionAccess { roles=Set.copyOf(roles); } }
public sealed interface StepResult permits Done,Failed {} public record Done(String step) implements StepResult{} public record Failed(String step,String reason) implements StepResult{}
// Process Manager: owns the long-running workflow and compensation decisions.
public interface ProvisioningStep { StepResult execute(ProvisionAccess command); void compensate(ProvisionAccess command); }
public static final class ProvisioningProcessManager { private final List<ProvisioningStep> steps; public ProvisioningProcessManager(List<ProvisioningStep> steps){this.steps=List.copyOf(steps);} public StepResult run(ProvisionAccess command){var completed=new ArrayList<ProvisioningStep>();for(var step:steps){var result=step.execute(command);if(result instanceof Failed){Collections.reverse(completed);completed.forEach(s->s.compensate(command));return result;}completed.add(step);}return new Done("all");} }
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Process Manager, Command |
| Offene Restschuld | Produktionsadapter, Persistenz- und Lasttests bleiben umgebungsspezifisch. |
Simulation 12 · Report Generation 5 Refactoring-Runs
Erkannte Risiken
Format Conditionals, Memory Spikes, Mixed Query and Rendering
Zielmuster
Query Object, Strategy, Streaming Port
Run-Folge
- Characterization Tests und Verhaltensinventar
- Fachbegriffe und Verantwortlichkeiten extrahieren
- Seiteneffekte hinter Ports verschieben
- Änderungsachse mit Pattern kapseln
- Regressionstests, Architekturgrenzen und Restschulden dokumentieren
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.io.*; import java.util.*;
public final class ReportGenerationRefactoringSimulator {
private ReportGenerationRefactoringSimulator() {}
public record ReportQuery(String customerId, String period){}
public record Row(String label,long value){}
// Query Object: captures report intent without leaking persistence details.
public interface ReportDataPort { Iterable<Row> fetch(ReportQuery query); }
// Strategy Pattern: output formats are independently replaceable.
public interface ReportRenderer { void render(Iterable<Row> rows, Writer target) throws IOException; }
// Streaming Port: caller owns the target and avoids building one huge String.
public record ReportService(ReportDataPort data, Map<String,ReportRenderer> renderers){ public ReportService { renderers=Map.copyOf(renderers); } public void generate(String format, ReportQuery query, Writer target) throws IOException {var renderer=Optional.ofNullable(renderers.get(format)).orElseThrow();renderer.render(data.fetch(query),target);} }
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Query Object, Strategy, Streaming Port |
| Offene Restschuld | Produktionsadapter, Persistenz- und Lasttests bleiben umgebungsspezifisch. |
Kapitel 3 Vertragsänderungen und kontrollierte Migration6 Simulationen
Sechs Enterprise-Simulationen zu Verträgen, Eligibility, Refunds, Retention, Migration und Incident-Eskalation - mit Sicherheitsnetz, fünf Runs, Java-21-Code und kompakter SVG.
Refactoring Simulator
Sechs Enterprise-Simulationen zu Verträgen, Eligibility, Refunds, Retention, Migration und Incident-Eskalation - mit Sicherheitsnetz, fünf Runs, Java-21-Code und kompakter SVG.
6 Simulationen offen.
Simulation 13 · Contract Amendment 5 Refactoring-Runs
Erkannte Risiken
Mutable Contract, Scattered Validation, Audit Gaps
Zielmuster
Value Object, Specification, Domain Event
Run-Folge
- Characterization Tests sichern das beobachtete Verhalten
- Fachmodell und Verantwortlichkeiten werden explizit
- Regeln und Seiteneffekte werden getrennt
- Passende Patterns kapseln die echte Änderungsachse
- Regression, Architekturgrenzen und Restschulden werden dokumentiert
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.time.*; import java.util.*;
public final class ContractAmendmentRefactoringSimulator {
private ContractAmendmentRefactoringSimulator() {}
public record ContractId(String value) { public ContractId { if (value == null || value.isBlank()) throw new IllegalArgumentException("contract id"); } }
public record Amendment(ContractId contractId, LocalDate effectiveDate, Map<String,String> changes) { public Amendment { changes = Map.copyOf(changes); } }
// Design Pattern: Specification - amendment rules stay composable and independently testable.
public interface AmendmentSpecification { Optional<String> violation(Amendment amendment); }
// Domain Event - audit-relevant consequences are explicit and decoupled.
public record ContractAmended(ContractId contractId, LocalDate effectiveDate, Set<String> changedFields) { public ContractAmended { changedFields = Set.copyOf(changedFields); } }
public static final class AmendmentService {
private final List<AmendmentSpecification> specifications;
public AmendmentService(List<AmendmentSpecification> specifications){ this.specifications=List.copyOf(specifications); }
public ContractAmended apply(Amendment amendment){
var violations=specifications.stream().map(s->s.violation(amendment)).flatMap(Optional::stream).toList();
if(!violations.isEmpty()) throw new IllegalArgumentException(String.join("; ", violations));
return new ContractAmended(amendment.contractId(), amendment.effectiveDate(), amendment.changes().keySet());
}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Value Object, Specification, Domain Event |
| Restschuld | Produktionsadapter, Persistenz-, Last- und Integrationsprüfungen bleiben umgebungsspezifisch. |
Simulation 14 · Product Eligibility 5 Refactoring-Runs
Erkannte Risiken
Boolean Blindness, Rule Duplication, Channel Coupling
Zielmuster
Decision Object, Specification, Policy
Run-Folge
- Characterization Tests sichern das beobachtete Verhalten
- Fachmodell und Verantwortlichkeiten werden explizit
- Regeln und Seiteneffekte werden getrennt
- Passende Patterns kapseln die echte Änderungsachse
- Regression, Architekturgrenzen und Restschulden werden dokumentiert
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class ProductEligibilityRefactoringSimulator {
private ProductEligibilityRefactoringSimulator() {}
public record Customer(int age, String country, Set<String> segments) { public Customer { segments=Set.copyOf(segments); } }
public record Product(String code, int minimumAge, Set<String> countries) { public Product { countries=Set.copyOf(countries); } }
public record EligibilityDecision(boolean eligible, List<String> reasons) { public EligibilityDecision { reasons=List.copyOf(reasons); } }
// Design Pattern: Specification - each eligibility rule owns one reason for change.
public interface EligibilityRule { Optional<String> violation(Customer customer, Product product); }
// Policy Pattern - combines rules and returns a rich decision instead of a blind boolean.
public static final class EligibilityPolicy {
private final List<EligibilityRule> rules; public EligibilityPolicy(List<EligibilityRule> rules){this.rules=List.copyOf(rules);}
public EligibilityDecision decide(Customer customer, Product product){var reasons=rules.stream().map(r->r.violation(customer,product)).flatMap(Optional::stream).toList();return new EligibilityDecision(reasons.isEmpty(),reasons);}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Decision Object, Specification, Policy |
| Restschuld | Produktionsadapter, Persistenz-, Last- und Integrationsprüfungen bleiben umgebungsspezifisch. |
Simulation 15 · Refund Orchestration 5 Refactoring-Runs
Erkannte Risiken
Nested Conditions, Provider Leakage, Duplicate Side Effects
Zielmuster
State, Adapter, Idempotency Port
Run-Folge
- Characterization Tests sichern das beobachtete Verhalten
- Fachmodell und Verantwortlichkeiten werden explizit
- Regeln und Seiteneffekte werden getrennt
- Passende Patterns kapseln die echte Änderungsachse
- Regression, Architekturgrenzen und Restschulden werden dokumentiert
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class RefundOrchestrationRefactoringSimulator {
private RefundOrchestrationRefactoringSimulator() {}
public enum RefundState { REQUESTED, APPROVED, SENT, REJECTED }
public record Refund(String id,long amountCents,RefundState state){}
// Adapter Pattern - provider-specific APIs stay outside the use case.
public interface RefundProvider { String refund(String refundId,long amountCents); }
// Idempotency Port - duplicate requests cannot trigger duplicate money movement.
public interface RefundExecutionStore { boolean reserve(String refundId); void complete(String refundId,String providerReference); }
public record RefundService(RefundProvider provider, RefundExecutionStore store){
public String execute(Refund refund){if(refund.state()!=RefundState.APPROVED) throw new IllegalStateException("not approved");if(!store.reserve(refund.id())) return "already-processed";var reference=provider.refund(refund.id(),refund.amountCents());store.complete(refund.id(),reference);return reference;}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | State, Adapter, Idempotency Port |
| Restschuld | Produktionsadapter, Persistenz-, Last- und Integrationsprüfungen bleiben umgebungsspezifisch. |
Simulation 16 · Data Retention Workflow 5 Refactoring-Runs
Erkannte Risiken
Cron Script Logic, Hidden Legal Rules, Unsafe Deletion
Zielmuster
Policy, Command, Ports and Adapters
Run-Folge
- Characterization Tests sichern das beobachtete Verhalten
- Fachmodell und Verantwortlichkeiten werden explizit
- Regeln und Seiteneffekte werden getrennt
- Passende Patterns kapseln die echte Änderungsachse
- Regression, Architekturgrenzen und Restschulden werden dokumentiert
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.time.*; import java.util.*;
public final class DataRetentionRefactoringSimulator {
private DataRetentionRefactoringSimulator() {}
public record DataRecord(String id, Instant createdAt, String category, boolean legalHold){}
public record DeleteData(String recordId,String reason){}
// Policy Pattern - legal retention decisions are explicit and testable.
public interface RetentionPolicy { boolean mayDelete(DataRecord record, Instant now); }
// Ports and Adapters - destructive infrastructure stays behind a narrow boundary.
public interface DataDeletionPort { void delete(DeleteData command); }
public record RetentionService(RetentionPolicy policy, DataDeletionPort deletionPort){
public List<String> purge(Iterable<DataRecord> records, Instant now){var deleted=new ArrayList<String>();for(var record:records){if(policy.mayDelete(record,now)){deletionPort.delete(new DeleteData(record.id(),"retention-expired"));deleted.add(record.id());}}return List.copyOf(deleted);}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Policy, Command, Ports and Adapters |
| Restschuld | Produktionsadapter, Persistenz-, Last- und Integrationsprüfungen bleiben umgebungsspezifisch. |
Simulation 17 · Pricing Catalog Migration 5 Refactoring-Runs
Erkannte Risiken
Dual Model Drift, Big Bang Risk, Mapping Leakage
Zielmuster
Anti-Corruption Layer, Strangler Facade
Run-Folge
- Characterization Tests sichern das beobachtete Verhalten
- Fachmodell und Verantwortlichkeiten werden explizit
- Regeln und Seiteneffekte werden getrennt
- Passende Patterns kapseln die echte Änderungsachse
- Regression, Architekturgrenzen und Restschulden werden dokumentiert
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class PricingCatalogMigrationRefactoringSimulator {
private PricingCatalogMigrationRefactoringSimulator() {}
public record LegacyPrice(String sku,double amount,String currency){}
public record Money(long minorUnits,String currency){}
public record CatalogPrice(String sku,Money price){}
// Anti-Corruption Layer - translates the legacy model without contaminating the new domain.
public interface LegacyPricingAcl { Optional<CatalogPrice> find(String sku); }
public interface NewCatalog { Optional<CatalogPrice> find(String sku); }
// Strangler Facade - moves traffic gradually while preserving one stable client API.
public record PricingFacade(NewCatalog modern, LegacyPricingAcl legacy, Set<String> migratedSkus){
public PricingFacade { migratedSkus=Set.copyOf(migratedSkus); }
public Optional<CatalogPrice> find(String sku){return migratedSkus.contains(sku)?modern.find(sku):legacy.find(sku);}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Anti-Corruption Layer, Strangler Facade |
| Restschuld | Produktionsadapter, Persistenz-, Last- und Integrationsprüfungen bleiben umgebungsspezifisch. |
Simulation 18 · Incident Escalation 5 Refactoring-Runs
Erkannte Risiken
Timer Spaghetti, Lost Ownership, Notification Coupling
Zielmuster
State Machine, Process Manager, Notification Port
Run-Folge
- Characterization Tests sichern das beobachtete Verhalten
- Fachmodell und Verantwortlichkeiten werden explizit
- Regeln und Seiteneffekte werden getrennt
- Passende Patterns kapseln die echte Änderungsachse
- Regression, Architekturgrenzen und Restschulden werden dokumentiert
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.time.*; import java.util.*;
public final class IncidentEscalationRefactoringSimulator {
private IncidentEscalationRefactoringSimulator() {}
public enum Severity { LOW, HIGH, CRITICAL } public enum Status { OPEN, ACKNOWLEDGED, ESCALATED, RESOLVED }
public record Incident(String id,Severity severity,Status status,Instant openedAt){}
// State Machine - allowed transitions are explicit instead of scattered conditionals.
public interface IncidentStateMachine { Incident escalate(Incident incident, Instant now); }
public interface NotificationPort { void notify(String incidentId,String target,String message); }
// Process Manager - coordinates time-based escalation and external notifications.
public record EscalationProcessManager(IncidentStateMachine stateMachine, NotificationPort notifications){
public Incident evaluate(Incident incident, Instant now){if(incident.status()!=Status.OPEN) return incident;var escalated=stateMachine.escalate(incident,now);if(escalated.status()==Status.ESCALATED) notifications.notify(incident.id(),"on-call","Incident escalated");return escalated;}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | State Machine, Process Manager, Notification Port |
| Restschuld | Produktionsadapter, Persistenz-, Last- und Integrationsprüfungen bleiben umgebungsspezifisch. |
Kapitel 4 Kreditentscheidung und nachvollziehbare Policies6 Simulationen
Sechs Enterprise-Simulationen zu Kreditentscheidung, Lagerauffüllung, Consent, Settlement, SLA und Tenant-Migration.
Refactoring Simulator
Sechs Enterprise-Simulationen zu Kreditentscheidung, Lagerauffüllung, Consent, Settlement, SLA und Tenant-Migration.
6 Simulationen offen.
Simulation 19 · Loan Underwriting 5 Refactoring-Runs
Erkannte Risiken
Scattered Risk Rules, Boolean Decisions, External Bureau Coupling
Zielmuster
Specification, Decision Object, Adapter
Run-Folge
- Characterization Tests sichern das bestehende Verhalten
- Fachmodell und Zustände werden typisiert
- Regeln, Orchestrierung und Seiteneffekte werden getrennt
- Patterns kapseln die tatsächlichen Änderungsachsen
- Regression, Architekturgrenzen und Restschulden werden dokumentiert
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class LoanUnderwritingRefactoringSimulator {
private LoanUnderwritingRefactoringSimulator() {}
public record Application(String id, long incomeCents, long requestedCents, int age) {}
public record CreditSnapshot(int score, long openDebtCents) {}
public record Decision(boolean approved, List<String> reasons) { public Decision { reasons=List.copyOf(reasons); } }
// Adapter Pattern: shields the use case from a provider-specific credit bureau API.
public interface CreditBureauPort { CreditSnapshot load(String applicationId); }
// Specification Pattern: each risk rule stays independently testable and composable.
public interface UnderwritingRule { Optional<String> violation(Application application, CreditSnapshot snapshot); }
public record UnderwritingService(CreditBureauPort bureau, List<UnderwritingRule> rules) {
public UnderwritingService { rules=List.copyOf(rules); }
public Decision decide(Application application) {
var snapshot=bureau.load(application.id());
var reasons=rules.stream().map(r->r.violation(application,snapshot)).flatMap(Optional::stream).toList();
return new Decision(reasons.isEmpty(),reasons);
}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Specification, Decision Object, Adapter |
| Restschuld | Produktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch. |
Simulation 20 · Warehouse Replenishment 5 Refactoring-Runs
Erkannte Risiken
Magic Thresholds, Duplicate Ordering, Vendor Logic in Domain
Zielmuster
Policy, Idempotency Port, Strategy
Run-Folge
- Characterization Tests sichern das bestehende Verhalten
- Fachmodell und Zustände werden typisiert
- Regeln, Orchestrierung und Seiteneffekte werden getrennt
- Patterns kapseln die tatsächlichen Änderungsachsen
- Regression, Architekturgrenzen und Restschulden werden dokumentiert
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class WarehouseReplenishmentRefactoringSimulator {
private WarehouseReplenishmentRefactoringSimulator() {}
public record Stock(String sku,int available,int reserved,int reorderPoint) { public int free(){return available-reserved;} }
public record ReplenishmentOrder(String key,String sku,int quantity,String vendor) {}
// Policy Pattern: replenishment quantity is explicit business policy.
public interface ReplenishmentPolicy { int quantityFor(Stock stock); }
// Strategy Pattern: vendor selection can vary independently from stock policy.
public interface VendorStrategy { String vendorFor(String sku); }
// Idempotency Port: one shortage creates at most one open order.
public interface OrderReservationPort { boolean reserve(String key); void save(ReplenishmentOrder order); }
public record ReplenishmentService(ReplenishmentPolicy policy,VendorStrategy vendors,OrderReservationPort orders) {
public Optional<ReplenishmentOrder> evaluate(Stock stock){
if(stock.free()>stock.reorderPoint()) return Optional.empty();
var key=stock.sku()+":"+stock.reorderPoint(); if(!orders.reserve(key)) return Optional.empty();
var order=new ReplenishmentOrder(key,stock.sku(),policy.quantityFor(stock),vendors.vendorFor(stock.sku())); orders.save(order); return Optional.of(order);
}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Policy, Idempotency Port, Strategy |
| Restschuld | Produktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch. |
Simulation 21 · Consent Lifecycle 5 Refactoring-Runs
Erkannte Risiken
Mutable Flags, Missing History, Channel-Specific Side Effects
Zielmuster
State Machine, Domain Event, Ports and Adapters
Run-Folge
- Characterization Tests sichern das bestehende Verhalten
- Fachmodell und Zustände werden typisiert
- Regeln, Orchestrierung und Seiteneffekte werden getrennt
- Patterns kapseln die tatsächlichen Änderungsachsen
- Regression, Architekturgrenzen und Restschulden werden dokumentiert
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.time.*; import java.util.*;
public final class ConsentLifecycleRefactoringSimulator {
private ConsentLifecycleRefactoringSimulator() {}
public enum Status { REQUESTED, GRANTED, REVOKED, EXPIRED }
public record Consent(String id,String subject,Status status,Instant validUntil) {}
public sealed interface ConsentEvent permits ConsentGranted,ConsentRevoked {}
public record ConsentGranted(String consentId,Instant at) implements ConsentEvent {}
public record ConsentRevoked(String consentId,Instant at,String reason) implements ConsentEvent {}
// State Machine: legal transitions are centralized instead of hidden in mutable flags.
public static final class ConsentStateMachine {
public Consent grant(Consent c,Instant now){if(c.status()!=Status.REQUESTED) throw new IllegalStateException("grant not allowed");return new Consent(c.id(),c.subject(),Status.GRANTED,c.validUntil());}
public Consent revoke(Consent c){if(c.status()!=Status.GRANTED) throw new IllegalStateException("revoke not allowed");return new Consent(c.id(),c.subject(),Status.REVOKED,c.validUntil());}
}
// Ports and Adapters: persistence and notification are outside the domain transition.
public interface EventPort { void publish(ConsentEvent event); }
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | State Machine, Domain Event, Ports and Adapters |
| Restschuld | Produktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch. |
Simulation 22 · Settlement Batch 5 Refactoring-Runs
Erkannte Risiken
Giant Loop, Partial Writes, Provider-Specific Mapping
Zielmuster
Pipeline, Unit of Work, Adapter
Run-Folge
- Characterization Tests sichern das bestehende Verhalten
- Fachmodell und Zustände werden typisiert
- Regeln, Orchestrierung und Seiteneffekte werden getrennt
- Patterns kapseln die tatsächlichen Änderungsachsen
- Regression, Architekturgrenzen und Restschulden werden dokumentiert
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class SettlementBatchRefactoringSimulator {
private SettlementBatchRefactoringSimulator() {}
public record SettlementLine(String account,long amountCents,String currency) {}
public record SettlementBatch(String id,List<SettlementLine> lines) { public SettlementBatch { lines=List.copyOf(lines); } }
// Adapter Pattern: maps a provider file into the stable domain batch.
public interface SettlementReader { SettlementBatch read(byte[] payload); }
// Pipeline Pattern: validation and normalization form explicit processing stages.
public interface SettlementStage { SettlementBatch apply(SettlementBatch batch); }
// Unit of Work: all postings commit together or roll back together.
public interface SettlementUnitOfWork { void post(SettlementLine line); void commit(); void rollback(); }
public record SettlementService(List<SettlementStage> stages,SettlementUnitOfWork uow) {
public SettlementService { stages=List.copyOf(stages); }
public void process(SettlementBatch input){try{var batch=input;for(var stage:stages)batch=stage.apply(batch);for(var line:batch.lines())uow.post(line);uow.commit();}catch(RuntimeException ex){uow.rollback();throw ex;}}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Pipeline, Unit of Work, Adapter |
| Restschuld | Produktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch. |
Simulation 23 · SLA Breach Handling 5 Refactoring-Runs
Erkannte Risiken
Polling Spaghetti, Duplicate Alerts, Escalation Rules in Scheduler
Zielmuster
Specification, Process Manager, Notification Port
Run-Folge
- Characterization Tests sichern das bestehende Verhalten
- Fachmodell und Zustände werden typisiert
- Regeln, Orchestrierung und Seiteneffekte werden getrennt
- Patterns kapseln die tatsächlichen Änderungsachsen
- Regression, Architekturgrenzen und Restschulden werden dokumentiert
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.time.*; import java.util.*;
public final class SlaBreachRefactoringSimulator {
private SlaBreachRefactoringSimulator() {}
public record WorkItem(String id,String queue,Instant dueAt,boolean completed,int escalationLevel) {}
// Specification Pattern: breach criteria are explicit and testable.
public interface BreachSpecification { boolean breached(WorkItem item,Instant now); }
public interface NotificationPort { void send(String target,String message); }
public interface EscalationStore { boolean reserve(String workItemId,int level); void save(WorkItem item); }
// Process Manager: coordinates time, deduplication, state change and notification.
public record BreachProcessManager(BreachSpecification spec,EscalationStore store,NotificationPort notifications) {
public Optional<WorkItem> evaluate(WorkItem item,Instant now){if(!spec.breached(item,now))return Optional.empty();int next=item.escalationLevel()+1;if(!store.reserve(item.id(),next))return Optional.empty();var escalated=new WorkItem(item.id(),item.queue(),item.dueAt(),item.completed(),next);store.save(escalated);notifications.send(item.queue(),"SLA breach "+item.id()+" level "+next);return Optional.of(escalated);}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Specification, Process Manager, Notification Port |
| Restschuld | Produktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch. |
Simulation 24 · Tenant Migration 5 Refactoring-Runs
Erkannte Risiken
Shared Mutable Config, Big Bang Cutover, Cross-Tenant Leakage
Zielmuster
Strangler Facade, Anti-Corruption Layer, Migration State
Run-Folge
- Characterization Tests sichern das bestehende Verhalten
- Fachmodell und Zustände werden typisiert
- Regeln, Orchestrierung und Seiteneffekte werden getrennt
- Patterns kapseln die tatsächlichen Änderungsachsen
- Regression, Architekturgrenzen und Restschulden werden dokumentiert
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class TenantMigrationRefactoringSimulator {
private TenantMigrationRefactoringSimulator() {}
public enum MigrationState { LEGACY, SHADOW, MODERN }
public record TenantRoute(String tenantId,MigrationState state) {}
public record CustomerView(String id,String displayName) {}
// Anti-Corruption Layer: legacy data is translated into the modern read model.
public interface LegacyCustomerAcl { Optional<CustomerView> find(String tenantId,String customerId); }
public interface ModernCustomerPort { Optional<CustomerView> find(String tenantId,String customerId); }
public interface TenantRoutePort { TenantRoute route(String tenantId); }
// Strangler Facade: routing changes per tenant without a global cutover.
public record CustomerFacade(TenantRoutePort routes,LegacyCustomerAcl legacy,ModernCustomerPort modern) {
public Optional<CustomerView> find(String tenantId,String customerId){return switch(routes.route(tenantId).state()){case LEGACY->legacy.find(tenantId,customerId);case MODERN->modern.find(tenantId,customerId);case SHADOW->{var old=legacy.find(tenantId,customerId);modern.find(tenantId,customerId);yield old;}};}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Strangler Facade, Anti-Corruption Layer, Migration State |
| Restschuld | Produktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch. |
Kapitel 5 Kontoschließung, Seiteneffekte und Prozessgrenzen6 Simulationen
Die letzten sechs Enterprise-Simulationen schließen den Simulationsbereich vollständig ab.
Refactoring Simulator
Die letzten sechs Enterprise-Simulationen schließen den Simulationsbereich vollständig ab.
0 Simulationen offen.
Simulation 25 · Account Closure Workflow 5 Refactoring-Runs
Erkannte Risiken
Partial Cleanup, Lost Events, Unclear Completion State
Zielmuster
Process Manager, Transactional Outbox, State Machine
Run-Folge
- Characterization Tests sichern das bestehende Verhalten
- Fachmodell und Zustände werden typisiert
- Regeln, Orchestrierung und Seiteneffekte werden getrennt
- Patterns kapseln die tatsächlichen Änderungsachsen
- Regression, Architekturgrenzen und Restschulden werden dokumentiert
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.time.*; import java.util.*;
public final class AccountClosureRefactoringSimulator {
private AccountClosureRefactoringSimulator() {}
public enum Status { REQUESTED, BLOCKED, EXECUTING, COMPLETED }
public record Closure(String accountId, Status status, Set<String> completedSteps, Instant updatedAt) {
public Closure { completedSteps=Set.copyOf(completedSteps); }
}
public sealed interface ClosureEvent permits ClosureCompleted {}
public record ClosureCompleted(String accountId, Instant at) implements ClosureEvent {}
// Process Manager Pattern: coordinates independent cleanup steps without a giant transaction.
public interface ClosureStep { String name(); void execute(String accountId); }
// Transactional Outbox Pattern: state and publication intent are persisted atomically.
public interface ClosureStore { Closure load(String accountId); void saveWithEvent(Closure closure, ClosureEvent event); }
public record ClosureProcessManager(List<ClosureStep> steps, ClosureStore store, Clock clock) {
public ClosureProcessManager { steps=List.copyOf(steps); }
public Closure execute(String accountId) {
var current=store.load(accountId); var done=new HashSet<>(current.completedSteps());
for(var step:steps) if(done.add(step.name())) step.execute(accountId);
var completed=new Closure(accountId,Status.COMPLETED,done,clock.instant());
store.saveWithEvent(completed,new ClosureCompleted(accountId,clock.instant())); return completed;
}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Process Manager, Transactional Outbox, State Machine |
| Restschuld | Produktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch. |
Simulation 26 · Regulatory Reporting 5 Refactoring-Runs
Erkannte Risiken
Duplicated Mapping, Inconsistent Snapshots, Provider-Specific Formats
Zielmuster
Pipeline, Snapshot, Adapter
Run-Folge
- Characterization Tests sichern das bestehende Verhalten
- Fachmodell und Zustände werden typisiert
- Regeln, Orchestrierung und Seiteneffekte werden getrennt
- Patterns kapseln die tatsächlichen Änderungsachsen
- Regression, Architekturgrenzen und Restschulden werden dokumentiert
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.time.*; import java.util.*;
public final class RegulatoryReportingRefactoringSimulator {
private RegulatoryReportingRefactoringSimulator() {}
public record ReportingSnapshot(Instant asOf, List<Position> positions) { public ReportingSnapshot { positions=List.copyOf(positions); } }
public record Position(String account,String instrument,long quantity,long marketValueCents) {}
// Snapshot Pattern: every report is based on one immutable point-in-time view.
public interface SnapshotPort { ReportingSnapshot capture(Instant asOf); }
// Pipeline Pattern: enrichment, validation and aggregation remain explicit stages.
public interface ReportingStage { ReportingSnapshot apply(ReportingSnapshot snapshot); }
// Adapter Pattern: each regulator format stays outside the domain pipeline.
public interface ReportAdapter { byte[] render(ReportingSnapshot snapshot); }
public record ReportingService(SnapshotPort snapshots,List<ReportingStage> stages,ReportAdapter adapter) {
public ReportingService { stages=List.copyOf(stages); }
public byte[] create(Instant asOf){var s=snapshots.capture(asOf);for(var stage:stages)s=stage.apply(s);return adapter.render(s);}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Pipeline, Snapshot, Adapter |
| Restschuld | Produktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch. |
Simulation 27 · Identity Verification 5 Refactoring-Runs
Erkannte Risiken
Provider Branches, Hidden Retry Rules, Mixed Risk and Transport Logic
Zielmuster
Chain of Responsibility, Policy, Ports and Adapters
Run-Folge
- Characterization Tests sichern das bestehende Verhalten
- Fachmodell und Zustände werden typisiert
- Regeln, Orchestrierung und Seiteneffekte werden getrennt
- Patterns kapseln die tatsächlichen Änderungsachsen
- Regression, Architekturgrenzen und Restschulden werden dokumentiert
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class IdentityVerificationRefactoringSimulator {
private IdentityVerificationRefactoringSimulator() {}
public record Applicant(String id,String country,int age,Map<String,String> evidence){public Applicant{evidence=Map.copyOf(evidence);}}
public record VerificationResult(boolean verified,List<String> reasons){public VerificationResult{reasons=List.copyOf(reasons);}}
// Policy Pattern: country and product rules remain independent from providers.
public interface VerificationPolicy { Optional<String> violation(Applicant applicant); }
// Ports and Adapters: provider-specific identity checks are behind a stable port.
public interface IdentityProviderPort { VerificationResult verify(Applicant applicant); }
// Chain of Responsibility: local policies short-circuit before expensive remote checks.
public record VerificationService(List<VerificationPolicy> policies,IdentityProviderPort provider) {
public VerificationService { policies=List.copyOf(policies); }
public VerificationResult verify(Applicant applicant){var reasons=policies.stream().map(p->p.violation(applicant)).flatMap(Optional::stream).toList();return reasons.isEmpty()?provider.verify(applicant):new VerificationResult(false,reasons);}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Chain of Responsibility, Policy, Ports and Adapters |
| Restschuld | Produktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch. |
Simulation 28 · Pricing Rollout 5 Refactoring-Runs
Erkannte Risiken
Big Bang Release, Duplicate Implementations, No Safe Fallback
Zielmuster
Feature Toggle, Branch by Abstraction, Strategy
Run-Folge
- Characterization Tests sichern das bestehende Verhalten
- Fachmodell und Zustände werden typisiert
- Regeln, Orchestrierung und Seiteneffekte werden getrennt
- Patterns kapseln die tatsächlichen Änderungsachsen
- Regression, Architekturgrenzen und Restschulden werden dokumentiert
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class PricingRolloutRefactoringSimulator {
private PricingRolloutRefactoringSimulator() {}
public record PriceRequest(String tenant,String product,long baseCents) {}
public record PriceQuote(long amountCents,String engine) {}
// Strategy Pattern: old and new pricing engines share a stable contract.
public interface PricingEngine { PriceQuote quote(PriceRequest request); }
// Feature Toggle Pattern: rollout decisions are explicit and reversible per tenant.
public interface RolloutPolicy { boolean useModernEngine(String tenant); }
// Branch by Abstraction: callers depend on one facade while implementations coexist.
public record PricingFacade(RolloutPolicy rollout,PricingEngine legacy,PricingEngine modern) {
public PriceQuote quote(PriceRequest request){return rollout.useModernEngine(request.tenant())?modern.quote(request):legacy.quote(request);}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Feature Toggle, Branch by Abstraction, Strategy |
| Restschuld | Produktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch. |
Simulation 29 · Partner Onboarding 5 Refactoring-Runs
Erkannte Risiken
Boolean Checklist, Manual Handoffs, Missing Ownership
Zielmuster
State Machine, Specification, Process Manager
Run-Folge
- Characterization Tests sichern das bestehende Verhalten
- Fachmodell und Zustände werden typisiert
- Regeln, Orchestrierung und Seiteneffekte werden getrennt
- Patterns kapseln die tatsächlichen Änderungsachsen
- Regression, Architekturgrenzen und Restschulden werden dokumentiert
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.util.*;
public final class PartnerOnboardingRefactoringSimulator {
private PartnerOnboardingRefactoringSimulator() {}
public enum Status { DRAFT, REVIEW, CONTRACTING, ACTIVATION, ACTIVE, REJECTED }
public record Partner(String id,Status status,Map<String,String> facts){public Partner{facts=Map.copyOf(facts);}}
// Specification Pattern: onboarding requirements are independently testable.
public interface Requirement { Optional<String> missing(Partner partner); }
public interface PartnerStore { void save(Partner partner); }
public interface TaskPort { void assign(String partnerId,String task); }
// Process Manager Pattern: moves the partner and creates the next operational task.
public record OnboardingProcessManager(List<Requirement> requirements,PartnerStore store,TaskPort tasks) {
public OnboardingProcessManager { requirements=List.copyOf(requirements); }
public Partner submit(Partner partner){var missing=requirements.stream().map(r->r.missing(partner)).flatMap(Optional::stream).toList();if(!missing.isEmpty())throw new IllegalStateException(String.join(", ",missing));var next=new Partner(partner.id(),Status.REVIEW,partner.facts());store.save(next);tasks.assign(next.id(),"COMPLIANCE_REVIEW");return next;}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | State Machine, Specification, Process Manager |
| Restschuld | Produktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch. |
Simulation 30 · Compliance Data Export 5 Refactoring-Runs
Erkannte Risiken
Unbounded Memory, Leaking Fields, Missing Audit Trail
Zielmuster
Specification, Streaming Port, Domain Event
Run-Folge
- Characterization Tests sichern das bestehende Verhalten
- Fachmodell und Zustände werden typisiert
- Regeln, Orchestrierung und Seiteneffekte werden getrennt
- Patterns kapseln die tatsächlichen Änderungsachsen
- Regression, Architekturgrenzen und Restschulden werden dokumentiert
Finaler Java-21-Code
Finaler Java-21-Codepackage com.aydinsude.workbench.simulator;
import java.time.*; import java.util.*; import java.util.stream.*;
public final class ComplianceDataExportRefactoringSimulator {
private ComplianceDataExportRefactoringSimulator() {}
public record ExportRequest(String subjectId,Set<String> scopes){public ExportRequest{scopes=Set.copyOf(scopes);}}
public record ExportRow(String category,Map<String,String> values){public ExportRow{values=Map.copyOf(values);}}
public record ExportCompleted(String subjectId,long rowCount,Instant at) {}
// Specification Pattern: field release rules are explicit and composable.
public interface ExportPolicy { boolean allowed(ExportRequest request,ExportRow row); }
// Streaming Port: large exports do not require full in-memory materialization.
public interface ExportSink { void begin(ExportRequest request); void write(ExportRow row); void complete(); }
public interface AuditEventPort { void publish(ExportCompleted event); }
public record ExportService(ExportPolicy policy,ExportSink sink,AuditEventPort events,Clock clock) {
public long export(ExportRequest request,Stream<ExportRow> rows){sink.begin(request);long count=0;try(var stream=rows){for(var it=stream.iterator();it.hasNext();){var row=it.next();if(policy.allowed(request,row)){sink.write(row);count++;}}}sink.complete();events.publish(new ExportCompleted(request.subjectId(),count,clock.instant()));return count;}
}
}| Prüfpunkt | Ergebnis |
|---|---|
| Sicherheitsnetz | Characterization- und gezielte Unit-Tests |
| Pattern | Specification, Streaming Port, Domain Event |
| Restschuld | Produktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch. |