Stop Building Code “Shit Mountains” – 10 Java Clean‑Code Techniques
This article presents ten practical Java clean‑code techniques—from meaningful naming and single‑purpose methods to avoiding magic numbers, writing purposeful comments, proper logging, defensive programming, DTO separation, Stream API usage, Optional handling, and safe ThreadPoolExecutor configuration—each illustrated with concrete code examples and explanations.
1. Introduction
Many developers inherit legacy Java projects that feel like a "code wasteland" filled with outdated classes, ad‑hoc log statements, obscure variable names, and tangled if‑else logic, creating a deep technical‑debt abyss.
2. Clean‑Code Techniques
2.1 Meaningful Naming
A clear name eliminates the need for extra comments. Use domain‑specific nouns and verbs so the method’s intent is obvious.
public List<User> get(String type) { /* ... */ }Bad example – the name conveys no purpose.
public List<User> findActiveUsersByDepartment(String departmentCode) { /* ... */ }Good example – the method name describes exactly what it does.
2.2 Small, Focused Functions
Each function should do one thing (Single Responsibility Principle), reducing debugging effort.
public void placeOrder(Order order) { /* 30+ lines */ }Bad example – mixes validation, discount, ID generation, notification.
public void placeOrder(Order order) {
// 订单验证
validateOrderDetails(order);
// 1.验证订单详情
validatePaymentMethod(order);
// 2.验证支付方式
// 订单处理
processStockDeduction(order);
calculateFinalPrice(order);
createOrderRecord(order);
notifyCustomer(order);
}Good example – each step is a separate, testable method.
2.3 Avoid Magic Numbers
Hard‑coded literals hide meaning and cause confusion. if (user.getStatus() == 1) { /* ... */ } Bad example – the meaning of 1 is unclear.
public static final int USER_STATUS_ACTIVE = 1;
if (user.getStatus() == USER_STATUS_ACTIVE) { /* ... */ }Using a constant or an enum makes the intent explicit.
2.4 Purposeful Comments
Good code is self‑explanatory; comments should explain *why* something is done, not *what* the code already shows.
// 计算折扣价格
double discountPrice = originalPrice * discountRate;Bad example – repeats obvious information.
// 为会员提供额外10%折扣(会员专享策略,参考促销规则PR-305)
if (user.isMember()) {
discountPrice = originalPrice * (discountRate - 0.1);
}2.5 Logging as a Black Box
Logs should tell a story: who did what, when, and why.
// 更新患者病历记录
log.info("患者病历更新完成");Bad example – lacks context.
// 记录完整的操作上下文,便于后续审计和问题排查
// 医生[ID:1001]在[2025-01-01 11:30:22]更新了患者[ID:2005]的病历记录
// 修改内容:将过敏史从"青霉素过敏"更新为"青霉素过敏、头孢过敏"
// 修改原因:患者复诊时报告新过敏反应(见诊疗记录DR-20240315-005)
log.info("患者病历记录更新 [患者ID:{}] [医生ID:{}] [操作时间:{}] " +
"[原过敏史:{}] [新过敏史:{}] [修改原因:{}]",
2005L, 1001L, Instant.now(),
"青霉素", "青霉素, 头孢",
"患者复诊报告新增过敏反应");Use appropriate log levels and avoid logging sensitive data.
2.6 Defensive Programming
Validate inputs early to fail fast and prevent hidden NPEs.
// 假设从外部API获取的交易数据可能为null
TransactionData data = fetchTransactionFromExternalAPI();
BigDecimal amount = data.getPayment().getAmount()
.multiply(new BigDecimal("1.1"));
if (data.getStatus().equals("PENDING")) {
processPayment(amount);
}Bad example – no null checks, unchecked status.
// 1.显式校验输入有效性
TransactionData data = Optional.ofNullable(fetchTransactionFromExternalAPI())
.orElseThrow(() -> new InvalidInputException("交易数据为空"));
Objects.requireNonNull(data.getPayment(), "支付信息缺失");
Objects.requireNonNull(data.getPayment().getAmount(), "交易金额缺失");
if (!"PENDING".equals(data.getStatus())) {
throw new IllegalStateException("仅允许处理PENDING状态的交易");
}
BigDecimal amount = data.getPayment().getAmount()
.multiply(new BigDecimal("1.1"))
.setScale(2, RoundingMode.HALF_UP);
processPayment(amount);2.7 DTO vs Entity Separation
Entities represent database tables; DTOs expose only required data to callers, preventing accidental leakage.
// Bad: returning entity directly
return userRepository.findById(id);
// Good: map to DTO
User user = userRepository.findById(id);
return new UserDTO(user.getId(), user.getUsername()); // password omitted2.8 Stream API to Escape Loop Hell
Streams improve readability when used sensibly.
// Bad: manual map, nested if, explicit collection
Map<String, List<User>> map = new HashMap<>();
for (User user : users) {
if (user.isActive()) {
map.computeIfAbsent(user.getDepartment(), k -> new ArrayList<>()).add(user);
}
}
// Good: declarative pipeline
Map<String, List<User>> map = users.stream()
.filter(User::isActive)
.collect(Collectors.groupingBy(User::getDepartment));2.9 Optional for Elegant Null Handling
Wrap potentially null values in Optional and chain transformations safely.
// Bad: nested null checks
String city = null;
if (user != null) {
Address address = user.getAddress();
if (address != null) {
city = address.getCity();
}
}
// Good: Optional pipeline
String city = Optional.ofNullable(user)
.map(User::getAddress)
.map(Address::getCity)
.orElse("Unknown");2.10 ThreadPoolExecutor Configuration
Never use Executors.newFixedThreadPool() in production; it creates an unbounded queue that can cause OOM.
// Bad: unbounded queue
ExecutorService pool = Executors.newFixedThreadPool(10);
// Good: explicit bounded queue and rejection policy
ThreadPoolExecutor pool = new ThreadPoolExecutor(
5, // core threads
10, // max threads
60, TimeUnit.SECONDS, // keep‑alive time
new ArrayBlockingQueue<>(100), // bounded queue
new ThreadPoolExecutor.CallerRunsPolicy() // rejection handler
);Define core size, queue capacity, and rejection strategy to avoid resource exhaustion.
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.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
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.
