Skip to content

代码风格规范

📏 统一规范:确保代码风格一致性,提高代码可读性和可维护性

📋 目录


注释规范

基本原则

  • 不要添加无意义的注释
  • 代码应该自解释
  • 注释解释"为什么"而不是"做什么"

注释位置

java
// ✅ 正确:独立行注释
// 这是正确的注释方式
queryWrapper.eq(Entity::getField, value);

// ✅ 正确:多行注释放在代码块上方
// 排除已拒绝的申请
.ne(Entity::getAPPROVALSTATUS, "REJECTED")
// 排除已取消的申请  
.ne(Entity::getAPPROVALSTATUS, "CANCELLED");

// ❌ 错误:避免行尾注释
queryWrapper.eq(Entity::getField, value);  // 这是错误的注释方式

类和方法注释

java
/**
 * 费用报销服务实现类
 * 
 * @author 作者名
 * @date 2024-08-14
 */
@Service
public class ExpenseClaimServiceImpl {
    
    /**
     * 提交报销单
     * 
     * @param id 报销单ID
     * @throws BusinessException 业务异常
     */
    public void submit(String id) {
        // 方法实现
    }
}

特殊注释标记

java
// TODO: 待实现的功能
// FIXME: 需要修复的问题
// HACK: 临时解决方案
// NOTE: 重要说明
// ⚠️ 警告:这里有潜在问题

代码格式

缩进和空格

  • 使用4个空格缩进,不使用Tab
  • 操作符两边加空格
  • 逗号后面加空格
java
// ✅ 正确的格式
if (condition) {
    int result = a + b;
    list.add(item1, item2, item3);
}

// ❌ 错误的格式
if(condition){
    int result=a+b;
    list.add(item1,item2,item3);
}

大括号使用

java
// ✅ 正确:即使单行也使用大括号
if (condition) {
    doSomething();
}

// ❌ 错误:省略大括号
if (condition)
    doSomething();

行长度限制

  • 每行不超过120个字符
  • 长语句合理换行
java
// ✅ 正确:合理换行
String result = someVeryLongMethodName(
    parameter1,
    parameter2,
    parameter3
);

// 链式调用换行
queryWrapper.eq(Entity::getField1, value1)
           .ne(Entity::getField2, value2)
           .like(Entity::getField3, value3);

导入规范

导入顺序

java
// 1. Java标准库
import java.util.*;
import java.io.*;

// 2. 第三方库
import org.springframework.*;
import com.mybatisflex.*;

// 3. 项目内部包
import jpwise.base.*;
import jpwise.util.*;
import jpwise.model.*;

// 4. 静态导入
import static jpwise.constant.Constants.*;

避免通配符导入

java
// ✅ 正确:明确导入
import java.util.List;
import java.util.Map;
import java.util.HashMap;

// ❌ 错误:使用通配符
import java.util.*;

常用导入清单

java
// Controller层
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import javax.validation.Valid;
import jpwise.base.ActionResult;
import jpwise.annotation.BuildQuery;

// Service层
import org.springframework.stereotype.Service;
import com.mybatisflex.annotation.UseDataSource;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jpwise.database.constant.DbNameConst;

// 工具类
import jpwise.util.JsonUtil;
import jpwise.util.StringUtil;
import jpwise.util.DateUtil;
import jpwise.util.RandomUtil;

依赖注入

统一使用@Autowired

java
// ✅ 正确:使用@Autowired
@Autowired
private UserService userService;

@Autowired
private RedisUtil redisUtil;

// ❌ 错误:避免使用@Resource
@Resource
private UserService userService;

构造器注入(推荐)

java
// ✅ 最佳实践:构造器注入
@Service
public class BusinessServiceImpl {
    
    private final UserService userService;
    private final RedisUtil redisUtil;
    
    @Autowired
    public BusinessServiceImpl(UserService userService, RedisUtil redisUtil) {
        this.userService = userService;
        this.redisUtil = redisUtil;
    }
}

异常处理

使用项目定义的异常

java
// ✅ 正确:使用项目异常类
import jpwise.exception.BusinessException;
import jpwise.exception.DataException;

if (businessConditionFails) {
    throw new BusinessException("业务异常信息");
}

if (dataValidationFails) {
    throw new DataException("数据验证失败");
}

// ❌ 错误:使用通用异常
throw new Exception("错误");
throw new RuntimeException("错误");

异常声明一致性

java
// ✅ 正确:与基类保持一致
@Override
public Map<String, Object> beforeSave(Map<String, Object> dic, Boolean isNew) 
       throws BusinessException, DataException {
    // 实现
}

// ❌ 错误:随意声明
@Override
public Map<String, Object> beforeSave(Map<String, Object> dic, Boolean isNew) 
       throws Exception {
    // 错误:throws声明与基类不一致
}

异常处理原则

java
// 1. 具体处理
try {
    // 业务逻辑
} catch (BusinessException e) {
    // 处理业务异常
    log.error("业务异常:{}", e.getMessage());
    throw e;
} catch (Exception e) {
    // 处理其他异常
    log.error("未知异常", e);
    throw new BusinessException("操作失败");
}

// 2. 资源清理
try {
    // 使用资源
} finally {
    // 确保资源释放
    if (connection != null) {
        connection.close();
    }
}

// 3. 使用try-with-resources
try (InputStream input = new FileInputStream(file)) {
    // 自动关闭资源
}

日志规范

强制使用@Slf4j注解

⚠️ 重要规则:所有Service实现类必须添加@Slf4j注解和对应的import语句。

Basic继承体系开发

java
import lombok.extern.slf4j.Slf4j;
import com.mybatisflex.annotation.UseDataSource;
import jpwise.database.constant.DbNameConst;

@Slf4j  // 必须添加日志注解
@Service
@UseDataSource(DbNameConst.JPWISE_DEMO)
public class UserServiceImpl extends BasicDemoServiceImpl<UserMapper, UserEntity> 
                            implements UserService {
    // 实现内容
}

纯手工开发方式

java
import lombok.extern.slf4j.Slf4j;
import com.mybatisflex.annotation.UseDataSource;
import com.mybatisflex.spring.service.impl.ServiceImpl;

@Slf4j  // 必须添加日志注解
@Service
@UseDataSource(DbNameConst.JPWISE_DEMO)
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, BusinessEntity> 
                                implements BusinessService {
    // 实现内容
}

使用Slf4j记录日志

java
@Slf4j
@Service
public class BusinessService {
    
    public void businessMethod() {
        log.info("开始执行业务方法");
        log.debug("调试信息:{}", debugData);
        log.warn("警告信息");
        log.error("错误信息", exception);
    }
}

日志级别使用

  • ERROR: 错误,需要立即处理
  • WARN: 警告,潜在问题
  • INFO: 重要业务信息
  • DEBUG: 调试信息

日志最佳实践

java
// ✅ 使用占位符
log.info("用户{}执行了{}操作", userId, operation);

// ❌ 字符串拼接
log.info("用户" + userId + "执行了" + operation + "操作");

// ✅ 记录异常
log.error("操作失败", e);

// ✅ 避免在循环中打日志
for (Item item : items) {
    // 处理逻辑
}
log.info("处理了{}条记录", items.size());

接口设计

RESTful规范

java
// ✅ 正确:只使用GET和POST
@GetMapping              // 查询操作
@PostMapping            // 创建、更新、删除操作

// ❌ 错误:使用其他方法
@PutMapping             // 不使用
@DeleteMapping          // 不使用
@PatchMapping          // 不使用

URL命名规范

java
// ✅ 正确的URL设计
@RequestMapping("/api/extend/User")           // 资源名称
@GetMapping                                   // GET /api/extend/User
@GetMapping("/{id}")                          // GET /api/extend/User/{id}
@PostMapping                                  // POST /api/extend/User
@PostMapping("/update/{id}")                  // POST /api/extend/User/update/{id}
@PostMapping("/{id}")                         // POST /api/extend/User/{id} (删除)

// 批量操作
@PostMapping("/Actions/Import")               // 导入
@PostMapping("/Actions/Export")               // 导出

统一返回格式

java
// ✅ 始终使用ActionResult
@GetMapping
public ActionResult<List<Entity>> getList() {
    return ActionResult.success(data);
}

@PostMapping
public ActionResult<String> create(@RequestBody Entity entity) {
    return ActionResult.success(MsgCode.SU001.get());
}

// ❌ 错误:直接返回数据
@GetMapping
public List<Entity> getList() {
    return data;  // 错误:没有包装
}

其他规范

常量定义

java
// ✅ 使用常量类
public class StatusConstant {
    public static final String DRAFT = "DRAFT";
    public static final String PENDING = "PENDING";
    public static final String APPROVED = "APPROVED";
}

// 使用
if (StatusConstant.DRAFT.equals(entity.getStatus())) {
    // 处理
}

空值处理

java
// ✅ 使用工具类处理
if (StringUtil.isNotEmpty(str)) {
    // 处理
}

String value = StringUtil.nvl(nullableValue, "default");

// ✅ 使用Optional(Java 8+)
Optional<Entity> optional = Optional.ofNullable(entity);
optional.ifPresent(e -> {
    // 处理
});

集合操作

java
// ✅ 判空后操作
if (list != null && !list.isEmpty()) {
    // 处理
}

// ✅ 使用Stream API
List<String> result = list.stream()
    .filter(StringUtil::isNotEmpty)
    .map(String::toUpperCase)
    .collect(Collectors.toList());

方法设计原则

java
// 1. 单一职责
public void saveUser(User user) {
    validateUser(user);    // 验证
    saveToDatabase(user);  // 保存
    sendNotification(user); // 通知
}

// 2. 参数不超过3个
// ✅ 好的设计
public void updateUser(String id, UserDTO dto);

// ❌ 参数过多
public void updateUser(String id, String name, String email, String phone, String address);

// 3. 返回值明确
public boolean deleteUser(String id);  // 明确返回操作结果
public User getUser(String id);        // 可能返回null,需要文档说明

代码审查清单

Controller层

  • [ ] 使用@BuildQuery注解在方法上
  • [ ] 返回ActionResult包装
  • [ ] 使用@Valid验证参数
  • [ ] 只使用GET和POST方法

Service层

  • [ ] 添加@Slf4j注解和对应import
  • [ ] 添加@UseDataSource注解
  • [ ] 使用@Transactional管理事务
  • [ ] 使用项目工具类
  • [ ] 正确处理异常

通用要求

  • [ ] 代码格式规范
  • [ ] 注释清晰
  • [ ] 没有硬编码
  • [ ] 日志记录合理
  • [ ] 异常处理完善

💡 提示:良好的代码规范是团队协作的基础,遵循统一的规范可以显著提高代码质量和开发效率。