Clean Code Practices: Naming, Method Length, Nesting Reduction, and Useful Libraries
The article shares practical clean‑code guidelines for Java developers, covering how code serves as team communication, the importance of clear naming, keeping methods short, reducing nested if/else, extracting try/catch blocks, encapsulating many parameters, and leveraging Lombok and Apache Commons utilities.
Code as a Team Communication Tool
Beyond emails and face‑to‑face talks, code itself conveys design intent; clear structure and good comments let teammates understand and maintain features without constant clarification.
Keep the Camp Cleaner Than When You Arrived
Just as scouts clean their campsite, developers should follow established coding standards and reuse shared libraries instead of introducing redundant or conflicting implementations.
Appropriate Naming
Good names are as crucial as naming a newborn. Teams should agree on domain‑specific terms (e.g., using canteen consistently) and avoid misleading abbreviations.
Bad Example
// 手机号
String phone = "13421800409";
// 获取地址
private String getDiZhi();
//修改密码
private void modifyPassword(String password1 ,String password2)Good Example
// 手机号 mobileNo比phone更精确
String mobileNo = "13421800409";
// 避免英文拼音混杂
private String getAddress();
// 参数的命名要区分意义
private void modifyPassword(String oldPassowrd, String newPassword)Short Methods
Methods should be concise; extremely long methods (e.g., 500 lines) hinder readability. Split complex logic into smaller, focused methods.
Bad Example
private UserDTO getUserDTO(Integer userId) {
//获取基本信息 …10行
//获取最近的一次订单信息 …30行
//获取钱包、可用优惠券张数等 …30行
return userDTO;
}Good Example
private UserDTO getUserDTO(Integer userId) {
UserDTO userDTO = getUserBasicInfo(userId);
userDTO.setUserLastOrder(getUserLastOrder(userId));
userDTO.setUserAccount(getUserAccount(userId));
return userDTO;
}
private UserDTO getUserBasicInfo(Integer userId);
private UserLastOrder getUserLastOrder(Integer userId);
private UserAccount getUserAccount(Integer userId);Reduce if/else Nesting
Deep nesting makes code hard to follow. Guard clauses (early returns) simplify the flow.
Bad Example
public boolean modifyPassword(Integer userId, String oldPassword, String newPassword) {
if (userId != null && StringUtils.isNotBlank(newPassword) && SpringUtils.isNotBlank(oldPassword)) {
User user = getUserById(userId);
if (user != null) {
if (user.getPassword().equals(oldPassword)) {
return updatePassword(userId, newPassword);
}
}
}
return false;
}Good Example
public Boolean modifyPassword(Integer userId, String oldPassword, String newPassword) {
if (userId == null || StringUtils.isBlank(newPassword) || StringUtils.isBlank(oldPassword)) {
return false;
}
User user = getUserById(userId);
if (user == null) {
return false;
}
if (!user.getPassword().equals(oldPassword)) {
return false;
}
return updatePassword(userId, newPassword);
}Extract try/catch
Long methods wrapped in a single try/catch hide where errors occur. Isolate risky operations into separate methods with their own handling.
Bad Example
private UserDTO getUserDTO(Integer userId) {
try {
// many lines ...
} catch (Exception e) {
logger.error(e);
return null;
}
return userDTO;
}Good Example
private UserDTO getUserDTO(Integer userId) {
UserDTO userDTO = getUserBasicInfo(userId);
userDTO.setUserLastOrder(getUserLastOrder(userId));
userDTO.setUserAccount(getUserAccount(userId));
return userDTO;
}
private UserDTO getUserBasicInfo(Integer userId) { /* ... */ }
private UserLastOrder getUserLastOrder(Integer userId) { /* ... */ }
private UserAccount getUserAccount(Integer userId) {
try {
// TODO
} catch (Exception e) {
// TODO
}
}Encapsulate Multiple Parameters
If a method needs more than three arguments, wrap them in a DTO to avoid long signatures and improve readability.
Bad Example
public Page<Order> queryOrderByPage(Integer current, Integer size, String productName, Integer userId, Date startTime, Date endTime, BigDecimal minAmount, BigDecimal maxAmount) { }Good Example
@Getter @Setter
public class OrderQueryDTO extends PageDTO {
private String productName;
private Integer userId;
private Date startTime;
private Date endTime;
private BigDecimal minAmount;
private BigDecimal maxAmount;
}
public Page<Order> queryOrderByPage(OrderQueryDTO orderQueryDTO) { }Third‑Party Libraries
Lombok
Lombok generates constructors, getters/setters, equals, hashCode, and toString methods at compile time via annotations.
@Getter @Setter
public class Order {
private Integer userId;
}Apache Commons
Apache Commons provides utilities for collections, strings, IO, etc.
// Example: check if a collection is empty
CollectionUtils.isEmpty(null); // true
CollectionUtils.isEmpty(new ArrayList()); // true
CollectionUtils.isEmpty(Arrays.asList("a", "b")); // false(End of article)
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
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.
