Backend Development 21 min read

Eliminating Code Duplication in Java Business Logic with Design Patterns, Annotations, and Bean Mapping

This article explains how to reduce repetitive Java business code by applying the factory and template‑method patterns for shopping‑cart processing, using custom annotations with reflection to generate API requests, and leveraging bean‑mapping utilities to copy properties between DTO/DO objects, while illustrating each technique with concrete code examples.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Eliminating Code Duplication in Java Business Logic with Design Patterns, Annotations, and Bean Mapping

Many developers complain that business code lacks technical depth because it often consists of simple CRUD operations, but the author argues that design patterns, OOP, and advanced Java features are essential for maintainable large‑scale projects.

The first solution tackles three similar shopping‑cart implementations (Normal, VIP, Internal) by extracting common logic into an AbstractCart class and using the template‑method pattern; each subclass overrides only the discount and delivery calculations. The factory pattern, combined with Spring's IoC container, selects the appropriate cart implementation based on user type, eliminating duplicated if‑else branches.

public abstract class AbstractCart {
    public Cart process(long userId, Map
items) {
        // common initialization, item conversion, total calculations
    }
    protected abstract void processCouponPrice(long userId, Item item);
    protected abstract void processDeliveryPrice(long userId, Item item);
}

The second solution shows how to replace repetitive parameter‑formatting code for bank APIs with custom annotations ( @BankAPI and @BankAPIField ) and a single reflective remoteCall method that builds the fixed‑length request string, adds an MD5 signature, and sends the HTTP request.

private static String remoteCall(AbstractAPI api) throws IOException {
    BankAPI bankAPI = api.getClass().getAnnotation(BankAPI.class);
    StringBuilder sb = new StringBuilder();
    Arrays.stream(api.getClass().getDeclaredFields())
        .filter(f -> f.isAnnotationPresent(BankAPIField.class))
        .sorted(Comparator.comparingInt(f -> f.getAnnotation(BankAPIField.class).order()))
        .peek(f -> f.setAccessible(true))
        .forEach(f -> {
            BankAPIField field = f.getAnnotation(BankAPIField.class);
            Object value = "";
            try { value = f.get(api); } catch (IllegalAccessException e) { e.printStackTrace(); }
            // format based on field.type()
        });
    // append signature and send request
    return result;
}

The third solution addresses the tedious manual copying between DTO, DO, and VO objects. Instead of writing dozens of setter calls, a bean‑mapping utility such as BeanUtils.copyProperties(source, target, "id") copies matching fields automatically while allowing ignored properties, dramatically reducing human error.

In summary, the article demonstrates three practical ways to eliminate duplicated code: (1) extract common behavior into abstract classes with the template‑method pattern, (2) use annotations and reflection to centralize repetitive processing logic, and (3) employ property‑copy tools for object transformation, all of which improve maintainability and adhere to the open‑closed principle.

Design PatternsJavaReflectioncode refactoringAnnotationsFactory Patterntemplate method
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

login 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.