AI-Driven DDD Refactoring: From Monolithic Service Packages to Modular Architecture
Using AI to assist domain-driven design, this case study details how a monolithic Taobao service-package system was analyzed, restructured, and refactored, reducing development effort from 5-8 person-days per package to configuration-based implementation while eliminating duplicated code and improving modularity, testability, and scalability.
Background
The service‑package business grew rapidly, exposing severe inefficiencies in the monolithic code base. Adding a new service‑package type required 5‑8 person‑days, modifications to eight core files and 200‑300 lines of code.
High development cost : repetitive changes across many files.
Code duplication : product‑type judgment logic duplicated in ten files.
Strong coupling : a 3800‑line service class mixed product, price, contract and other domain logic.
High extension risk : any new feature could introduce regressions.
Refactoring Goals
AI‑driven domain analysis : use AI to analyse the existing code, automatically identify bounded contexts and assist in designing a DDD model.
Intelligent model implementation : let AI generate domain models, service interfaces and data‑conversion code, dramatically reducing manual effort.
Continuous model optimisation : establish an AI‑driven code‑quality monitoring system to assess architecture health, complexity and duplication.
Cost reduction : shrink the effort of adding a new service‑package from 5‑8 person‑days to a configuration‑based implementation.
Sustainable architecture evolution : build a smart architecture that supports rapid business changes and technology upgrades.
Architecture Design Phase
AI‑assisted Bounded‑Context Extraction
The AI was prompted with the request “You are a DDD expert, abstract the bounded contexts from the existing code under package v6.” It produced an initial context split based on package structure, but the result lacked deep business semantics.
Human Refinement
Domain experts corrected the coarse split, producing a refined bounded‑context diagram that aligns with actual business semantics.
Iterative AI Fine‑Tuning
Using the manually corrected contexts, the AI iteratively refined each context. For the product context it generated a detailed domain model, service and repository definitions.
Code Implementation Phase
Skeleton Generation from Technical Document
Based on the technical specification "Service Package Model Upgrade.md", the AI generated the initial code skeleton for the new v61.domain package.
@Override
public SingleResponse<ConfirmableServiceProgramDTO> queryConfirmableProgramList(ConfirmableProgramQuery query) {
try {
// step 1: parameter validation and shop info retrieval
if (query == null || query.getShopId() == null) {
return SingleResponse.buildFailure("Parameters cannot be null");
}
ShopInfoDTO shopInfo = shopQueryAbility.queryShopInfo(query.getShopId());
if (shopInfo == null) {
return SingleResponse.buildFailure("Shop does not exist");
}
// step 2: fetch confirmable program list – complex extension points
List<ServiceProgramDTO> programs = new ArrayList<>();
List<GoodsDTO> allGoods = goodsQueryAbility.queryAllGoods();
for (GoodsDTO goods : allGoods) {
// product‑type judgment logic – issue 1
if (switch51ConfigGateway.superClientGoodId().equals(goods.getGoodsId())) {
if (validateSuperClientGoods(goods, shopInfo)) {
ServiceProgramDTO program = buildSuperClientProgram(goods, shopInfo);
programs.add(program);
}
} else if (switch51ConfigGateway.platformDeliveryGoodId().equals(goods.getGoodsId())) {
if (validatePlatformDeliveryGoods(goods, shopInfo)) {
ServiceProgramDTO program = buildPlatformDeliveryProgram(goods, shopInfo);
programs.add(program);
}
} else if (switch51ConfigGateway.selfDeliveryGoodId().equals(goods.getGoodsId())) {
if (validateSelfDeliveryGoods(goods, shopInfo)) {
ServiceProgramDTO program = buildSelfDeliveryProgram(goods, shopInfo);
programs.add(program);
}
}
// ... more product type checks
}
// step 3: price calculation – embedded in business service
for (ServiceProgramDTO program : programs) {
if (program.getDeliveryType().equals("PLATFORM")) {
program.setCommissionRate(new BigDecimal("0.08")); // 8%
program.setDeliveryFee(calculatePlatformDeliveryFee(program, shopInfo));
} else if (program.getDeliveryType().equals("SELF")) {
program.setCommissionRate(new BigDecimal("0.10")); // 10%
program.setDeliveryFee(calculateSelfDeliveryFee(program, shopInfo));
}
BigDecimal basePrice = priceCalculateAbility.calculateBasePrice(program.getGoodsId(), shopInfo.getCategoryId());
program.setBasePrice(basePrice);
}
// step 4: activity handling – scattered logic
List<ActivityDTO> activities = activityQueryAbility.queryShopActivities(query.getShopId());
for (ServiceProgramDTO program : programs) {
for (ActivityDTO activity : activities) {
if (activity.getType().equals("COMMISSION_DISCOUNT")) {
if (activity.getTargetGoods().contains(program.getGoodsId())) {
BigDecimal discountRate = activity.getDiscountRate();
BigDecimal newRate = program.getCommissionRate().subtract(discountRate);
program.setCommissionRate(newRate);
program.setActivityId(activity.getActivityId());
}
} else if (activity.getType().equals("DELIVERY_DISCOUNT")) {
if (activity.getTargetGoods().contains(program.getGoodsId())) {
BigDecimal discountFee = activity.getDiscountAmount();
BigDecimal newFee = program.getDeliveryFee().subtract(discountFee);
program.setDeliveryFee(newFee);
}
}
}
}
// step 5: build result DTO
ConfirmableServiceProgramDTO result = new ConfirmableServiceProgramDTO();
result.setShopId(query.getShopId());
result.setPrograms(programs);
result.setTotalCount(programs.size());
return SingleResponse.of(result);
} catch (Exception e) {
logger.error("Query confirmable program failed, shopId:{}, exception:{}", query.getShopId(), e.getMessage(), e);
return SingleResponse.buildFailure("Query failed");
}
}AI‑Assisted Refactoring
Case 1 – API conversion : The AI transformed a list of shopConfirmableContracts into ConfirmableServiceProgramDTO, adding 734 lines of code with only 25 manual corrections (96.6% accuracy).
Case 2 – Version comparison tool : A utility class ProgramVersionComparisonUtil was generated to compare the results of two queryConfirmableProgramList implementations. The AI produced 3,098 lines of code, required 12 manual fixes, and achieved 99.6% accuracy.
Refactoring Effect Analysis
Architecture Decoupling
Before refactoring the core method consisted of 42 lines and the call chain spanned ~1,500 lines, with heavy coupling and duplicated product‑type checks. After refactoring the core method was reduced to 37 lines and the call chain to ~720 lines, a 52% reduction in code volume and clear separation of responsibilities.
Code structure : reduced from 42+1,500 lines to 37+720 lines.
Responsibility separation : each bounded context now handles its own logic.
Product handling : unified product‑validation service eliminated duplicated checks.
Price calculation : isolated price service improved cohesion.
Activity processing : centralized activity service simplified maintenance.
Extensibility : new features require changes only in the relevant context.
Testability : each context can be unit‑tested independently, raising coverage.
Key Improvements
Code volume reduced by 52%.
Duplicate product‑type logic eliminated completely.
Price and activity logic moved to independent services.
Extension points now confined to single contexts, supporting the open‑closed principle.
Unit‑test coverage increased because each context is isolated.
Conclusion
The AI‑assisted architecture upgrade demonstrates the effectiveness of human‑machine collaboration. By automating repetitive coding tasks and focusing engineers on domain design, the team achieved substantial efficiency gains, reduced code duplication, and built a maintainable, extensible architecture for rapid business evolution.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
