When You Can’t Understand Someone Else’s Code, Is It Their Skill or Yours?

The article explains that difficulty reading code often stems from unfamiliar design patterns and complex construction logic rather than poor code quality, illustrating with factory and strategy patterns in inventory systems, and provides a checklist to distinguish between genuinely bad code and gaps in a developer’s knowledge.

samdeepthink
samdeepthink
samdeepthink
When You Can’t Understand Someone Else’s Code, Is It Their Skill or Yours?

Factory for Complex Object Construction

When constructing a business object requires multiple steps—fetching a template, generating a document number, converting data, and assembling an aggregate root—duplicating this logic leads to errors. Example from a stock‑taking module:

Query the stock‑taking template by ID to obtain name, type, and date rules.

Call a code‑generation service to produce a document number.

Transform each material entry into a detail entity.

Assemble all data into a complete aggregate‑root object.

Encapsulating these steps in a factory yields a single method that returns the fully built aggregate root.

@Component
public class StocktakingDocsFactory {
    private final CodeGeneratorService codeGeneratorService;
    private final StocktakingTemplateRepository templateRepository;

    public StocktakingDocsAggregateRoot create(SubmitStocktakingCommand command) {
        StocktakingTemplate template = templateRepository.getById(command.getTemplateId());
        String code = codeGeneratorService.generate(ModuleEnum.STOCKTAKING);
        List<StocktakingItemEntity> items = buildItems(command.getMaterialList());
        return StocktakingDocsAggregateRoot.builder()
                .code(code)
                .name(template.getName())
                .type(template.getType())
                .items(items)
                .build();
    }
}

Client code calls factory.create(command) and receives the aggregate root without exposing external calls or business rules.

Strategy Pattern for Variant Business Rules

In an inventory‑adjustment module, different scenarios (fulfillment deduction, initial stock‑in, stock‑taking adjustment, transfer/receipt/loss) require distinct handling. Packing all branches into a single if‑else method would create a large, fragile function.

Define a strategy interface:

public interface InventoryAdjustmentHandler {
    MaterialInventoryAggregateRoot execute(AdjustmentContext context);
    boolean isSupported(AdjustmentContext context);
}

Implement a handler for each scenario. Example: fulfillment deduction handler.

@Component
public class FulfillmentAdjustmentHandler implements InventoryAdjustmentHandler {
    public static final List<StatementType> TYPES = List.of(
            StatementType.PRODUCT_DEDUCTION, StatementType.PRODUCT_RETURNS);

    @Override
    public boolean isSupported(AdjustmentContext context) {
        return TYPES.contains(context.getStatementType());
    }

    @Override
    public MaterialInventoryAggregateRoot execute(AdjustmentContext context) {
        // Only deduct theoretical inventory
        context.getAggregateRoot().fulfillmentAdjustment(context.getDTO());
        return context.getAggregateRoot();
    }
}

The aggregate root discovers all handlers from the Spring context and lets each decide applicability:

public MaterialInventoryAggregateRoot adjustment(InventoryAdjustmentDTO dto) {
    Map<String, InventoryAdjustmentHandler> handlers =
            SpringUtils.getContext().getBeansOfType(InventoryAdjustmentHandler.class);
    handlers.forEach((key, handler) -> {
        AdjustmentContext context = new AdjustmentContext(this, dto, statementType);
        if (handler.isSupported(context)) {
            handler.execute(context);
        }
    });
    return this;
}

Adding a new adjustment scenario requires only a new handler class implementing isSupported and execute; existing handlers remain unchanged, limiting the impact of changes.

Extracting complex construction into factories and isolating variant rules with strategy handlers localizes changes, reduces maintenance risk, and supports extensibility.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

design patternsjavasoftware architectureStrategy PatternSpringFactory PatternCode Organization
samdeepthink
Written by

samdeepthink

Knowledge Planet: Old Dock's Tech Chronicles Zhihu: SamDeepThinking A technical manager who still codes heavily on the front line. From junior developer to tech lead, then tech manager, now leading the whole front‑ and back‑end development team—leveling up along the way. I have some insights on programming, career development, and tech management.

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.