From Simple Java Method to Over‑Engineered Design: Refactoring Strategies and Patterns
This article walks through a Java junior's code review, showing step‑by‑step how simple null‑checks evolve into constant definitions, static methods, enums, Optional usage, and finally strategy‑pattern implementations, illustrating both useful refactoring and the risk of over‑design.
All Beginnings
The author reviews a junior developer's Java code that simply converts external identifiers to internal ones, then shares optimization ideas that gradually lead to an over‑designed solution.
Original Simple Method
public Integer parseSaleType(String saleTypeStr) {
if (saleTypeStr == null || saleTypeStr.equals("")) {
return null;
}
if (saleTypeStr.equals("JX")) {
return 1;
}
return null;
}Syntax Guidelines
Prefer functional checks: Objects.isNull(saleTypeStr) instead of saleTypeStr == null.
Use StringUtils.isBlank(saleTypeStr) to handle null, empty, and whitespace strings.
Place constants on the left side of equality checks, e.g., "JX".equals(saleTypeStr).
Define magic values as private static final constants.
Make stateless methods static to avoid unnecessary object allocation.
Logic Simplification
The core logic is simply mapping a string to a number; the method can be reduced to:
public static Integer parseSaleType(String saleTypeStr) {
return "JX".equals(saleTypeStr) ? 1 : null;
}Or using Optional:
public static Integer parseSaleType(String saleTypeStr) {
return Optional.ofNullable(saleTypeStr)
.filter("JX"::equals)
.map(s -> 1)
.orElse(null);
}When a Separate Method Is Needed
If future extensions may add more branches, require context, or need frequent adjustments, keeping the method separate is justified.
Enum‑Based Refactoring
Define enums for string and integer representations:
public enum SaleTypeStrEnum { JX, /* OTHERS */ }
@AllArgsConstructor
@Getter
public enum SaleTypeIntEnum { JX(1); private Integer code; }Introduce a mapping enum to bind both values:
@Getter
@AllArgsConstructor
public enum SaleTypeRelEnum {
JX("JX", 1), /* OTHERS */;
private String fromCode;
private Integer toCode;
private static final Map<String, SaleTypeRelEnum> FROM_CODE_MAP =
Arrays.stream(values()).collect(Collectors.toMap(SaleTypeRelEnum::getFromCode, Function.identity()));
public static SaleTypeRelEnum get(String code) { return FROM_CODE_MAP.get(code); }
public static Integer parseCode(String code) {
return Optional.ofNullable(get(code)).map(SaleTypeRelEnum::getToCode).orElse(null);
}
}Strategy Pattern Extension
Define a parsing context and strategy interface:
public class SaleTypeParseContext {
private SaleTypeStrEnum saleTypeStr;
private SaleTypeParseStrategy parseStrategy;
public Integer parse() { return parseStrategy.parse(this); }
}
public interface SaleTypeParseStrategy {
Integer parse(SaleTypeParseContext ctx);
}Implement a concrete strategy for JX:
public class JxSaleTypeParseStrategy implements SaleTypeParseStrategy {
@Override
public Integer parse(SaleTypeParseContext ctx) { return SaleTypeIntEnum.JX.getCode(); }
}Provide a manual strategy container:
public class SaleTypeParseStrategyContainer {
public static final Map<SaleTypeStrEnum, SaleTypeParseStrategy> STRATEGY_MAP = new HashMap<>();
@PostConstruct
public void init() { STRATEGY_MAP.put(SaleTypeStrEnum.JX, new JxSaleTypeParseStrategy()); }
public Integer parse(SaleTypeParseContext ctx) {
return Optional.ofNullable(STRATEGY_MAP.get(ctx.getSaleTypeStr()))
.map(s -> s.parse(ctx))
.orElse(null);
}
}When using Spring, strategies can be auto‑registered and discovered via bean injection, allowing the container to remain unchanged as new strategies are added.
Further Extensions
Dynamic configuration switches (e.g., Diamond).
Expression evaluation with QLExpress.
Distributed calls via HSF providers.
Gateway‑based service routing.
Conclusion
The post is a note‑style exploration meant to spark thinking; it demonstrates both useful refactoring techniques and how easy it is to slip into over‑design.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Alibaba Cloud Developer
Alibaba's official tech channel, featuring all of its technology innovations.
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.
