How AI‑Driven DDD Refactoring Cut Service Package Development from Days to Hours

This article presents a detailed case study of using AI to assist domain‑driven design (DDD) for refactoring Taobao's monolithic flash‑sale service‑package system, showing how automated context extraction, code skeleton generation, and AI‑augmented implementation reduced development effort from 5‑8 person‑days to a configurable solution while improving architecture decoupling, code quality, and extensibility.

dbaplus Community
dbaplus Community
dbaplus Community
How AI‑Driven DDD Refactoring Cut Service Package Development from Days to Hours

Background

The Taobao flash‑sale service‑package system suffered from high development cost (adding a new package type required 5‑8 person‑days), extensive code duplication (product‑type judgment logic appeared in ten files), strong coupling (a 3800‑line monolithic service class mixed product, price, contract, and other domain logic), and high extension risk.

Refactoring Goals

AI‑driven architecture design : use AI to analyze existing code, automatically identify bounded contexts and context maps, and assist in designing a DDD model.

Automated model implementation : let AI generate repetitive artifacts such as domain models, service interfaces, and data‑conversion code.

Continuous model analysis : establish an AI‑driven quality‑monitoring system that evaluates architecture health, code complexity, and duplication.

Cost reduction : shrink the effort of adding a new service‑package type from 5‑8 person‑days to a configuration‑driven process.

Intelligent architectural evolution : build a sustainably evolving architecture that supports rapid business changes and technology upgrades.

AI‑Assisted Bounded‑Context Extraction

A prompt was sent to an AI model asking it to act as a DDD expert and abstract bounded contexts from the v6 package. The AI produced a diagram based solely on package structure, missing deeper business semantics. Engineers then manually refined the contexts, producing a corrected diagram and further used AI to fine‑tune the product context.

Code Generation and Implementation

Based on the technical document Technical‑Solution--Service‑Package‑Model‑Upgrade.md , the AI generated a skeleton for the v61.domain package. Two concrete cases illustrate the AI‑assisted development:

API conversion : converting List<shopConfirmableContracts> to ConfirmableServiceProgramDTO starting at line 157 of queryConfirmableProgramList. The AI added 734 lines, required 25 manual adjustments, and achieved 96.6 % accuracy.

Version‑comparison utility : a utility class ProgramVersionComparisonUtil was created to compare the results of two query methods. The AI added 3098 lines, needed 12 manual fixes, and reached 99.6 % accuracy.

After refactoring, the core method queryConfirmableProgramList follows a clear step‑by‑step flow, delegating responsibilities to dedicated domain services:

@Override
public SingleResponse<ConfirmableServiceProgramDTO> queryConfirmableProgramList(ConfirmableProgramQuery query) {
    // step 1: validate parameters and obtain shop info
    if (query == null || query.getShopId() == null) {
        return SingleResponse.buildFailure("参数不能为空");
    }
    ShopInfoDTO shopInfo = shopQueryAbility.queryShopInfo(query.getShopId());
    if (shopInfo == null) {
        return SingleResponse.buildFailure("门店不存在");
    }

    // step 2: fetch all goods
    List<GoodsDTO> allGoods = goodsQueryAbility.queryAllGoods();
    List<ServiceProgramDTO> programs = new ArrayList<>();
    for (GoodsDTO goods : allGoods) {
        // unified product‑type validation
        if (switch51ConfigGateway.superClientGoodId().equals(goods.getGoodsId())) {
            if (validateSuperClientGoods(goods, shopInfo)) {
                programs.add(buildSuperClientProgram(goods, shopInfo));
            }
        } else if (switch51ConfigGateway.platformDeliveryGoodId().equals(goods.getGoodsId())) {
            if (validatePlatformDeliveryGoods(goods, shopInfo)) {
                programs.add(buildPlatformDeliveryProgram(goods, shopInfo));
            }
        } else if (switch51ConfigGateway.selfDeliveryGoodId().equals(goods.getGoodsId())) {
            if (validateSelfDeliveryGoods(goods, shopInfo)) {
                programs.add(buildSelfDeliveryProgram(goods, shopInfo));
            }
        }
        // ... other product types
    }

    // step 3: price calculation (delegated to price service)
    for (ServiceProgramDTO program : programs) {
        if ("PLATFORM".equals(program.getDeliveryType())) {
            program.setCommissionRate(new BigDecimal("0.08"));
            program.setDeliveryFee(calculatePlatformDeliveryFee(program, shopInfo));
        } else if ("SELF".equals(program.getDeliveryType())) {
            program.setCommissionRate(new BigDecimal("0.10"));
            program.setDeliveryFee(calculateSelfDeliveryFee(program, shopInfo));
        }
        BigDecimal basePrice = priceCalculateAbility.calculateBasePrice(program.getGoodsId(), shopInfo.getCategoryId());
        program.setBasePrice(basePrice);
    }

    // step 4: activity handling (centralized activity service)
    List<ActivityDTO> activities = activityQueryAbility.queryShopActivities(query.getShopId());
    for (ServiceProgramDTO program : programs) {
        for (ActivityDTO activity : activities) {
            if ("COMMISSION_DISCOUNT".equals(activity.getType()) && activity.getTargetGoods().contains(program.getGoodsId())) {
                BigDecimal newRate = program.getCommissionRate().subtract(activity.getDiscountRate());
                program.setCommissionRate(newRate);
                program.setActivityId(activity.getActivityId());
            } else if ("DELIVERY_DISCOUNT".equals(activity.getType()) && activity.getTargetGoods().contains(program.getGoodsId())) {
                BigDecimal newFee = program.getDeliveryFee().subtract(activity.getDiscountAmount());
                program.setDeliveryFee(newFee);
            }
        }
    }

    // step 5: build response DTO
    ConfirmableServiceProgramDTO result = new ConfirmableServiceProgramDTO();
    result.setShopId(query.getShopId());
    result.setPrograms(programs);
    result.setTotalCount(programs.size());
    return SingleResponse.of(result);
}

Refactoring Effects

Architecture Decoupling

The call‑chain size of queryConfirmableProgramList dropped from ~1500 lines to ~720 lines (≈52 % reduction). Business logic was split into separate bounded contexts: shop, contract, goods, price, and activity.

Key Improvements

Code structure : main method reduced from 42 to 37 lines.

Duplicate elimination : product‑type judgment logic consolidated into a single validation service, achieving 100 % duplicate removal.

Price calculation : extracted to an independent price service.

Activity handling : centralized in an activity service.

Extensibility : adding a new product now touches only one or two context‑specific files.

Testability : each bounded context can be unit‑tested independently, raising overall test coverage.

Impact on Adding New Service Product

Prior to refactoring, introducing a new product required modifications in multiple core methods ( queryConfirmableProgramList, queryConfirmableCombineProgramList, signProgram) and several ability classes. After refactoring, the change is limited to updating the relevant bounded‑context service, the conversion class, and possibly the enum definition—typically only 1‑2 files.

Key Metrics

AI generated >70 % of the 3832 new lines of code.

Refactoring cycle shortened by more than 75 %.

Overall code volume reduced by 52 %.

Duplicate code eliminated completely.

Development cost for a new service package dropped from 5‑8 person‑days to a configuration‑driven process.

code generationArchitectureMicroservicesAIDomain-Driven Designrefactoring
dbaplus Community
Written by

dbaplus Community

Enterprise-level professional community for Database, BigData, and AIOps. Daily original articles, weekly online tech talks, monthly offline salons, and quarterly XCOPS&DAMS conferences—delivered by industry experts.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.