30 Simulationen

Refactoring Simulator

Alle zugehörigen Inhalte befinden sich auf dieser einen großen Seite. Kapitel und Beispiele sind standardmäßig geschlossen und lassen sich gezielt öffnen.

0 von 35 offen

5 Hauptkapitel · 30 enthaltene Lernbereiche · keine Navigation durch Einzeldateien nötig.

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.

Simulationsabschnitt 1

Refactoring Simulator

Sechs realistische Legacy-Situationen mit Sicherheitsnetz, fünf nachvollziehbaren Runs, finalem Java-Code und Architektur-SVG.

Simulationen: 6/30 Simulationen abgeschlossen

24 Simulationen offen.

Simulation 1 · God Order Service 5 Refactoring-Runs

God Order Service

Erkannte Risiken

God Class, Long Method, Primitive Obsession

Zielmuster

Strategy, Ports and Adapters

Run-Folge

  1. Characterization Test und Verhaltensinventar
  2. Verantwortlichkeiten und Fachbegriffe extrahieren
  3. Seiteneffekte hinter Ports verschieben
  4. Änderungsachse durch passendes Pattern kapseln
  5. Zielarchitektur, Regressionstests und Restschulden dokumentieren

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternStrategy, Ports and Adapters
Offene RestschuldProduktionsadapter und Lasttests bleiben umgebungsspezifisch.

Simulation 2 · Approval Rule Engine 5 Refactoring-Runs

Approval Rule Engine

Erkannte Risiken

Switch Explosion, Shotgun Surgery, Hidden Policy

Zielmuster

Specification, Composite

Run-Folge

  1. Characterization Test und Verhaltensinventar
  2. Verantwortlichkeiten und Fachbegriffe extrahieren
  3. Seiteneffekte hinter Ports verschieben
  4. Änderungsachse durch passendes Pattern kapseln
  5. Zielarchitektur, Regressionstests und Restschulden dokumentieren

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternSpecification, Composite
Offene RestschuldProduktionsadapter und Lasttests bleiben umgebungsspezifisch.

Simulation 3 · Batch Import Pipeline 5 Refactoring-Runs

Batch Import Pipeline

Erkannte Risiken

Mixed Abstraction, Error Swallowing, Resource Leak

Zielmuster

Pipeline, Result Type

Run-Folge

  1. Characterization Test und Verhaltensinventar
  2. Verantwortlichkeiten und Fachbegriffe extrahieren
  3. Seiteneffekte hinter Ports verschieben
  4. Änderungsachse durch passendes Pattern kapseln
  5. Zielarchitektur, Regressionstests und Restschulden dokumentieren

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternPipeline, Result Type
Offene RestschuldProduktionsadapter und Lasttests bleiben umgebungsspezifisch.

Simulation 4 · Notification Hub 5 Refactoring-Runs

Notification Hub

Erkannte Risiken

Conditional Dispatch, Tight Coupling, Duplicate Retry

Zielmuster

Adapter, Registry, Decorator

Run-Folge

  1. Characterization Test und Verhaltensinventar
  2. Verantwortlichkeiten und Fachbegriffe extrahieren
  3. Seiteneffekte hinter Ports verschieben
  4. Änderungsachse durch passendes Pattern kapseln
  5. Zielarchitektur, Regressionstests und Restschulden dokumentieren

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternAdapter, Registry, Decorator
Offene RestschuldProduktionsadapter und Lasttests bleiben umgebungsspezifisch.

Simulation 5 · Inventory Reservation 5 Refactoring-Runs

Inventory Reservation

Erkannte Risiken

Check-then-act Race, Shared Mutable State

Zielmuster

Repository, Atomic Operation

Run-Folge

  1. Characterization Test und Verhaltensinventar
  2. Verantwortlichkeiten und Fachbegriffe extrahieren
  3. Seiteneffekte hinter Ports verschieben
  4. Änderungsachse durch passendes Pattern kapseln
  5. Zielarchitektur, Regressionstests und Restschulden dokumentieren

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternRepository, Atomic Operation
Offene RestschuldProduktionsadapter und Lasttests bleiben umgebungsspezifisch.

Simulation 6 · Customer Merge Workflow 5 Refactoring-Runs

Customer Merge Workflow

Erkannte Risiken

Boolean Blindness, Temporal Coupling, Partial Updates

Zielmuster

Command, Unit of Work, Domain Event

Run-Folge

  1. Characterization Test und Verhaltensinventar
  2. Verantwortlichkeiten und Fachbegriffe extrahieren
  3. Seiteneffekte hinter Ports verschieben
  4. Änderungsachse durch passendes Pattern kapseln
  5. Zielarchitektur, Regressionstests und Restschulden dokumentieren

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternCommand, Unit of Work, Domain Event
Offene RestschuldProduktionsadapter 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.

Simulationsabschnitt 2

Refactoring Simulator

Sechs weitere Enterprise-Simulationen mit Sicherheitsnetz, fünf nachvollziehbaren Runs, finalem Java-21-Code und themenspezifischer Architektur-SVG.

Simulationen: 24/30 Simulationen abgeschlossen

6 Simulationen offen.

Simulation 7 · Subscription Renewal 5 Refactoring-Runs

Subscription Renewal

Erkannte Risiken

Temporal Coupling, Hidden Clock, Mixed Billing

Zielmuster

Clock Port, Policy, Command

Run-Folge

  1. Characterization Tests und Verhaltensinventar
  2. Fachbegriffe und Verantwortlichkeiten extrahieren
  3. Seiteneffekte hinter Ports verschieben
  4. Änderungsachse mit Pattern kapseln
  5. Regressionstests, Architekturgrenzen und Restschulden dokumentieren

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternClock Port, Policy, Command
Offene RestschuldProduktionsadapter, Persistenz- und Lasttests bleiben umgebungsspezifisch.

Simulation 8 · Fraud Case Triage 5 Refactoring-Runs

Fraud Case Triage

Erkannte Risiken

Rule Spaghetti, Priority Leakage, Boolean Blindness

Zielmuster

Specification, Chain of Responsibility

Run-Folge

  1. Characterization Tests und Verhaltensinventar
  2. Fachbegriffe und Verantwortlichkeiten extrahieren
  3. Seiteneffekte hinter Ports verschieben
  4. Änderungsachse mit Pattern kapseln
  5. Regressionstests, Architekturgrenzen und Restschulden dokumentieren

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternSpecification, Chain of Responsibility
Offene RestschuldProduktionsadapter, Persistenz- und Lasttests bleiben umgebungsspezifisch.

Simulation 9 · Invoice Reconciliation 5 Refactoring-Runs

Invoice Reconciliation

Erkannte Risiken

N+1 Reads, Partial Updates, Duplicate Matching

Zielmuster

Batch Repository, Unit of Work

Run-Folge

  1. Characterization Tests und Verhaltensinventar
  2. Fachbegriffe und Verantwortlichkeiten extrahieren
  3. Seiteneffekte hinter Ports verschieben
  4. Änderungsachse mit Pattern kapseln
  5. Regressionstests, Architekturgrenzen und Restschulden dokumentieren

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternBatch Repository, Unit of Work
Offene RestschuldProduktionsadapter, Persistenz- und Lasttests bleiben umgebungsspezifisch.

Simulation 10 · Shipment Routing 5 Refactoring-Runs

Shipment Routing

Erkannte Risiken

Switch Explosion, Provider Leakage, Hard-coded Fallback

Zielmuster

Strategy Registry, Adapter

Run-Folge

  1. Characterization Tests und Verhaltensinventar
  2. Fachbegriffe und Verantwortlichkeiten extrahieren
  3. Seiteneffekte hinter Ports verschieben
  4. Änderungsachse mit Pattern kapseln
  5. Regressionstests, Architekturgrenzen und Restschulden dokumentieren

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternStrategy Registry, Adapter
Offene RestschuldProduktionsadapter, Persistenz- und Lasttests bleiben umgebungsspezifisch.

Simulation 11 · Access Provisioning 5 Refactoring-Runs

Access Provisioning

Erkannte Risiken

Implicit Workflow, Compensating Actions Missing, Shared Flags

Zielmuster

Process Manager, Command

Run-Folge

  1. Characterization Tests und Verhaltensinventar
  2. Fachbegriffe und Verantwortlichkeiten extrahieren
  3. Seiteneffekte hinter Ports verschieben
  4. Änderungsachse mit Pattern kapseln
  5. Regressionstests, Architekturgrenzen und Restschulden dokumentieren

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternProcess Manager, Command
Offene RestschuldProduktionsadapter, Persistenz- und Lasttests bleiben umgebungsspezifisch.

Simulation 12 · Report Generation 5 Refactoring-Runs

Report Generation

Erkannte Risiken

Format Conditionals, Memory Spikes, Mixed Query and Rendering

Zielmuster

Query Object, Strategy, Streaming Port

Run-Folge

  1. Characterization Tests und Verhaltensinventar
  2. Fachbegriffe und Verantwortlichkeiten extrahieren
  3. Seiteneffekte hinter Ports verschieben
  4. Änderungsachse mit Pattern kapseln
  5. Regressionstests, Architekturgrenzen und Restschulden dokumentieren

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternQuery Object, Strategy, Streaming Port
Offene RestschuldProduktionsadapter, 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.

Simulationsabschnitt 3

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.

Simulationen: 24/30 Simulationen abgeschlossen

6 Simulationen offen.

Simulation 13 · Contract Amendment 5 Refactoring-Runs

Contract Amendment

Erkannte Risiken

Mutable Contract, Scattered Validation, Audit Gaps

Zielmuster

Value Object, Specification, Domain Event

Run-Folge

  1. Characterization Tests sichern das beobachtete Verhalten
  2. Fachmodell und Verantwortlichkeiten werden explizit
  3. Regeln und Seiteneffekte werden getrennt
  4. Passende Patterns kapseln die echte Änderungsachse
  5. Regression, Architekturgrenzen und Restschulden werden dokumentiert

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternValue Object, Specification, Domain Event
RestschuldProduktionsadapter, Persistenz-, Last- und Integrationsprüfungen bleiben umgebungsspezifisch.

Simulation 14 · Product Eligibility 5 Refactoring-Runs

Product Eligibility

Erkannte Risiken

Boolean Blindness, Rule Duplication, Channel Coupling

Zielmuster

Decision Object, Specification, Policy

Run-Folge

  1. Characterization Tests sichern das beobachtete Verhalten
  2. Fachmodell und Verantwortlichkeiten werden explizit
  3. Regeln und Seiteneffekte werden getrennt
  4. Passende Patterns kapseln die echte Änderungsachse
  5. Regression, Architekturgrenzen und Restschulden werden dokumentiert

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternDecision Object, Specification, Policy
RestschuldProduktionsadapter, Persistenz-, Last- und Integrationsprüfungen bleiben umgebungsspezifisch.

Simulation 15 · Refund Orchestration 5 Refactoring-Runs

Refund Orchestration

Erkannte Risiken

Nested Conditions, Provider Leakage, Duplicate Side Effects

Zielmuster

State, Adapter, Idempotency Port

Run-Folge

  1. Characterization Tests sichern das beobachtete Verhalten
  2. Fachmodell und Verantwortlichkeiten werden explizit
  3. Regeln und Seiteneffekte werden getrennt
  4. Passende Patterns kapseln die echte Änderungsachse
  5. Regression, Architekturgrenzen und Restschulden werden dokumentiert

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternState, Adapter, Idempotency Port
RestschuldProduktionsadapter, Persistenz-, Last- und Integrationsprüfungen bleiben umgebungsspezifisch.

Simulation 16 · Data Retention Workflow 5 Refactoring-Runs

Data Retention Workflow

Erkannte Risiken

Cron Script Logic, Hidden Legal Rules, Unsafe Deletion

Zielmuster

Policy, Command, Ports and Adapters

Run-Folge

  1. Characterization Tests sichern das beobachtete Verhalten
  2. Fachmodell und Verantwortlichkeiten werden explizit
  3. Regeln und Seiteneffekte werden getrennt
  4. Passende Patterns kapseln die echte Änderungsachse
  5. Regression, Architekturgrenzen und Restschulden werden dokumentiert

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternPolicy, Command, Ports and Adapters
RestschuldProduktionsadapter, Persistenz-, Last- und Integrationsprüfungen bleiben umgebungsspezifisch.

Simulation 17 · Pricing Catalog Migration 5 Refactoring-Runs

Pricing Catalog Migration

Erkannte Risiken

Dual Model Drift, Big Bang Risk, Mapping Leakage

Zielmuster

Anti-Corruption Layer, Strangler Facade

Run-Folge

  1. Characterization Tests sichern das beobachtete Verhalten
  2. Fachmodell und Verantwortlichkeiten werden explizit
  3. Regeln und Seiteneffekte werden getrennt
  4. Passende Patterns kapseln die echte Änderungsachse
  5. Regression, Architekturgrenzen und Restschulden werden dokumentiert

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternAnti-Corruption Layer, Strangler Facade
RestschuldProduktionsadapter, Persistenz-, Last- und Integrationsprüfungen bleiben umgebungsspezifisch.

Simulation 18 · Incident Escalation 5 Refactoring-Runs

Incident Escalation

Erkannte Risiken

Timer Spaghetti, Lost Ownership, Notification Coupling

Zielmuster

State Machine, Process Manager, Notification Port

Run-Folge

  1. Characterization Tests sichern das beobachtete Verhalten
  2. Fachmodell und Verantwortlichkeiten werden explizit
  3. Regeln und Seiteneffekte werden getrennt
  4. Passende Patterns kapseln die echte Änderungsachse
  5. Regression, Architekturgrenzen und Restschulden werden dokumentiert

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternState Machine, Process Manager, Notification Port
RestschuldProduktionsadapter, 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.

Simulationsabschnitt 4

Refactoring Simulator

Sechs Enterprise-Simulationen zu Kreditentscheidung, Lagerauffüllung, Consent, Settlement, SLA und Tenant-Migration.

Simulationen: 24/30 Simulationen abgeschlossen

6 Simulationen offen.

Simulation 19 · Loan Underwriting 5 Refactoring-Runs

Loan Underwriting

Erkannte Risiken

Scattered Risk Rules, Boolean Decisions, External Bureau Coupling

Zielmuster

Specification, Decision Object, Adapter

Run-Folge

  1. Characterization Tests sichern das bestehende Verhalten
  2. Fachmodell und Zustände werden typisiert
  3. Regeln, Orchestrierung und Seiteneffekte werden getrennt
  4. Patterns kapseln die tatsächlichen Änderungsachsen
  5. Regression, Architekturgrenzen und Restschulden werden dokumentiert

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternSpecification, Decision Object, Adapter
RestschuldProduktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch.

Simulation 20 · Warehouse Replenishment 5 Refactoring-Runs

Warehouse Replenishment

Erkannte Risiken

Magic Thresholds, Duplicate Ordering, Vendor Logic in Domain

Zielmuster

Policy, Idempotency Port, Strategy

Run-Folge

  1. Characterization Tests sichern das bestehende Verhalten
  2. Fachmodell und Zustände werden typisiert
  3. Regeln, Orchestrierung und Seiteneffekte werden getrennt
  4. Patterns kapseln die tatsächlichen Änderungsachsen
  5. Regression, Architekturgrenzen und Restschulden werden dokumentiert

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternPolicy, Idempotency Port, Strategy
RestschuldProduktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch.

Simulation 21 · Consent Lifecycle 5 Refactoring-Runs

Consent Lifecycle

Erkannte Risiken

Mutable Flags, Missing History, Channel-Specific Side Effects

Zielmuster

State Machine, Domain Event, Ports and Adapters

Run-Folge

  1. Characterization Tests sichern das bestehende Verhalten
  2. Fachmodell und Zustände werden typisiert
  3. Regeln, Orchestrierung und Seiteneffekte werden getrennt
  4. Patterns kapseln die tatsächlichen Änderungsachsen
  5. Regression, Architekturgrenzen und Restschulden werden dokumentiert

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternState Machine, Domain Event, Ports and Adapters
RestschuldProduktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch.

Simulation 22 · Settlement Batch 5 Refactoring-Runs

Settlement Batch

Erkannte Risiken

Giant Loop, Partial Writes, Provider-Specific Mapping

Zielmuster

Pipeline, Unit of Work, Adapter

Run-Folge

  1. Characterization Tests sichern das bestehende Verhalten
  2. Fachmodell und Zustände werden typisiert
  3. Regeln, Orchestrierung und Seiteneffekte werden getrennt
  4. Patterns kapseln die tatsächlichen Änderungsachsen
  5. Regression, Architekturgrenzen und Restschulden werden dokumentiert

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternPipeline, Unit of Work, Adapter
RestschuldProduktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch.

Simulation 23 · SLA Breach Handling 5 Refactoring-Runs

SLA Breach Handling

Erkannte Risiken

Polling Spaghetti, Duplicate Alerts, Escalation Rules in Scheduler

Zielmuster

Specification, Process Manager, Notification Port

Run-Folge

  1. Characterization Tests sichern das bestehende Verhalten
  2. Fachmodell und Zustände werden typisiert
  3. Regeln, Orchestrierung und Seiteneffekte werden getrennt
  4. Patterns kapseln die tatsächlichen Änderungsachsen
  5. Regression, Architekturgrenzen und Restschulden werden dokumentiert

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternSpecification, Process Manager, Notification Port
RestschuldProduktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch.

Simulation 24 · Tenant Migration 5 Refactoring-Runs

Tenant Migration

Erkannte Risiken

Shared Mutable Config, Big Bang Cutover, Cross-Tenant Leakage

Zielmuster

Strangler Facade, Anti-Corruption Layer, Migration State

Run-Folge

  1. Characterization Tests sichern das bestehende Verhalten
  2. Fachmodell und Zustände werden typisiert
  3. Regeln, Orchestrierung und Seiteneffekte werden getrennt
  4. Patterns kapseln die tatsächlichen Änderungsachsen
  5. Regression, Architekturgrenzen und Restschulden werden dokumentiert

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternStrangler Facade, Anti-Corruption Layer, Migration State
RestschuldProduktionsadapter 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.

Simulationsabschnitt 5

Refactoring Simulator

Die letzten sechs Enterprise-Simulationen schließen den Simulationsbereich vollständig ab.

Simulationen: 30/30 Simulationen abgeschlossen

0 Simulationen offen.

Simulation 25 · Account Closure Workflow 5 Refactoring-Runs

Account Closure Workflow

Erkannte Risiken

Partial Cleanup, Lost Events, Unclear Completion State

Zielmuster

Process Manager, Transactional Outbox, State Machine

Run-Folge

  1. Characterization Tests sichern das bestehende Verhalten
  2. Fachmodell und Zustände werden typisiert
  3. Regeln, Orchestrierung und Seiteneffekte werden getrennt
  4. Patterns kapseln die tatsächlichen Änderungsachsen
  5. Regression, Architekturgrenzen und Restschulden werden dokumentiert

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternProcess Manager, Transactional Outbox, State Machine
RestschuldProduktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch.

Simulation 26 · Regulatory Reporting 5 Refactoring-Runs

Regulatory Reporting

Erkannte Risiken

Duplicated Mapping, Inconsistent Snapshots, Provider-Specific Formats

Zielmuster

Pipeline, Snapshot, Adapter

Run-Folge

  1. Characterization Tests sichern das bestehende Verhalten
  2. Fachmodell und Zustände werden typisiert
  3. Regeln, Orchestrierung und Seiteneffekte werden getrennt
  4. Patterns kapseln die tatsächlichen Änderungsachsen
  5. Regression, Architekturgrenzen und Restschulden werden dokumentiert

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternPipeline, Snapshot, Adapter
RestschuldProduktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch.

Simulation 27 · Identity Verification 5 Refactoring-Runs

Identity Verification

Erkannte Risiken

Provider Branches, Hidden Retry Rules, Mixed Risk and Transport Logic

Zielmuster

Chain of Responsibility, Policy, Ports and Adapters

Run-Folge

  1. Characterization Tests sichern das bestehende Verhalten
  2. Fachmodell und Zustände werden typisiert
  3. Regeln, Orchestrierung und Seiteneffekte werden getrennt
  4. Patterns kapseln die tatsächlichen Änderungsachsen
  5. Regression, Architekturgrenzen und Restschulden werden dokumentiert

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternChain of Responsibility, Policy, Ports and Adapters
RestschuldProduktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch.

Simulation 28 · Pricing Rollout 5 Refactoring-Runs

Pricing Rollout

Erkannte Risiken

Big Bang Release, Duplicate Implementations, No Safe Fallback

Zielmuster

Feature Toggle, Branch by Abstraction, Strategy

Run-Folge

  1. Characterization Tests sichern das bestehende Verhalten
  2. Fachmodell und Zustände werden typisiert
  3. Regeln, Orchestrierung und Seiteneffekte werden getrennt
  4. Patterns kapseln die tatsächlichen Änderungsachsen
  5. Regression, Architekturgrenzen und Restschulden werden dokumentiert

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternFeature Toggle, Branch by Abstraction, Strategy
RestschuldProduktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch.

Simulation 29 · Partner Onboarding 5 Refactoring-Runs

Partner Onboarding

Erkannte Risiken

Boolean Checklist, Manual Handoffs, Missing Ownership

Zielmuster

State Machine, Specification, Process Manager

Run-Folge

  1. Characterization Tests sichern das bestehende Verhalten
  2. Fachmodell und Zustände werden typisiert
  3. Regeln, Orchestrierung und Seiteneffekte werden getrennt
  4. Patterns kapseln die tatsächlichen Änderungsachsen
  5. Regression, Architekturgrenzen und Restschulden werden dokumentiert

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternState Machine, Specification, Process Manager
RestschuldProduktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch.

Simulation 30 · Compliance Data Export 5 Refactoring-Runs

Compliance Data Export

Erkannte Risiken

Unbounded Memory, Leaking Fields, Missing Audit Trail

Zielmuster

Specification, Streaming Port, Domain Event

Run-Folge

  1. Characterization Tests sichern das bestehende Verhalten
  2. Fachmodell und Zustände werden typisiert
  3. Regeln, Orchestrierung und Seiteneffekte werden getrennt
  4. Patterns kapseln die tatsächlichen Änderungsachsen
  5. Regression, Architekturgrenzen und Restschulden werden dokumentiert

Finaler Java-21-Code

Finaler Java-21-Code
package 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üfpunktErgebnis
SicherheitsnetzCharacterization- und gezielte Unit-Tests
PatternSpecification, Streaming Port, Domain Event
RestschuldProduktionsadapter sowie Last-, Persistenz- und Integrationstests bleiben umgebungsspezifisch.
⌂ Cockpit