design-code
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "design-code" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-1f97748e55808ac2f62e74be8ecc5c4e42421d58d3345d016724c89ec72bec08. Verify the upstream source and version against https://skillhub.cn/skills/user_a4c2f3d2/design-code before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
skillhub.cn
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
A high-quality engineering coding design specification for coding, design and refactoring that strictly follows SOLID principles, emphasizing high cohesion, low coupling, and programming to abstractions. The specification covers layered responsibilities, transaction handling, query optimization, exception classification, logging, thread pools, SQL safety, and Stream guidelines, and applies to all coding, refactoring, and review scenarios.
Introduction source: third_party · user_a4c2f3d2 · 1.0.1 Reference
SkillPi interpretation
- Tasks
- Translation pending; see source documentation.
- Testing
- Not tested
Browse files
Frontmatter
name: design-code
description: "[PRD2PLAN] 高质量工程编码设计规范,严格遵循SOLID原则,高内聚低耦合,面向抽象编程。涵盖分层职责、事务、查询优化、异常分类、日志、线程池、SQL安全、Stream规范。适用于所有代码编写、重构、审查。"高质量工程编码设计规范
何时使用本规范
找到你的场景,直接跳转到对应章节:
| 场景 | 直接跳到 |
|---|---|
| 写新接口,不知道 Controller/Service/Repository 怎么分工 | 一、架构原则 → 分层职责 |
| 接手一个 300 行的 Service 方法,想拆分 | 三、代码质量 → 方法拆分 |
| Code Review 时,不确定某段代码是不是坑 | 典型错误对照清单 |
| 排查线上慢查询 / 内存高 | 五、性能 |
| 线上偶发报错没日志,定位不到问题 | 六、日志 |
| 多人同时操作同一条记录,数据被覆盖 | 四、健壮性 → 幂等 |
用 @Async 或开线程,TraceId 丢了 |
七、异步 |
| SQL 拼接报安全风险 / 排序字段不能写死 | 八、SQL 安全 |
代码里到处是 status == 1 / "admin" 字符串 |
九、常量与配置 |
| if-else 分支越来越多,想重构 | 十、设计模式原则 |
| 想看一个完整案例,从需求到代码 | 实战案例:订单状态流转 |
| 想知道某个坑怎么解决 | 常见问题速查(FAQ) |
一、架构原则
适用场景:设计新模块、选择分层方案、决定接口与实现关系
SOLID
- SRP: 每个类/方法只做一件事
- OCP: 对扩展开放,对修改封闭
- LSP: 子类可无缝替换父类
- ISP: 接口精简,按需拆分
- DIP: 依赖抽象,面向接口编程
分层职责(必须遵守)
适用场景:新需求开发、Code Review 时检查各层职责是否正确
| 层 | 允许 | 禁止 |
|---|---|---|
| Controller / Handler | 参数校验、调用 Service、组装响应 | 业务逻辑、数据库操作、数据转换 |
| Service / UseCase | 业务逻辑、事务管理、调用 Repository | 直接操作 HttpServletRequest/Response |
| Repository / Mapper / DAO | 数据访问、SQL 映射 | 业务逻辑 |
命名约定:
- Service 接口 + 实现类分离(如
I{Entity}Service→{Entity}ServiceImpl,或{Entity}Service→{Entity}ServiceImpl,项目内保持一致即可) - 查询统一使用查询构造器模式 + 私有方法封装动态条件(避免链式 if-null 臃肿)
二、统一响应与工具库
适用场景:定义接口响应格式、写 Service 查询方法、做对象拷贝
响应封装
统一使用项目内的标准响应包装类,所有接口返回一致的 JSON 结构:
success(data) // 200 - 成功
success("msg", data) // 200 - 带消息
failed("msg") // 业务异常(如 417/400)
failedWithConflict("msg") // 冲突(如 409)
serverError() // 服务器错误(500)
- 对象拷贝:使用项目统一的对象映射工具(如 BeanUtils / MapStruct / ModelMapper)
- 判空:使用项目统一的判空工具(如 StringUtils / ObjectUtils / CollectionUtils)
- JSON:使用项目统一的 JSON 库(如 Jackson / Gson / Fastjson)
查询构造器模式(通用)
// ✅ 标准:查询构造器 + 私有方法封装动态条件
QueryWrapper<Entity> w = new QueryWrapper<>();
addConditionIfPresent(w, Entity::getField, value);
// ✅ 批量操作:避免循环逐条查询
List<Long> ids = items.stream().map(Item::getId).collect(toList());
List<Entity> list = repository.findByIds(ids); // 批量查询,非循环单查
| 语言/框架 | 对应查询构造器 |
|---|---|
| Java / MyBatis-Plus | LambdaQueryWrapper |
| Java / JPA | Specification + CriteriaBuilder |
| C# / EF Core | IQueryable + LINQ |
| Go / GORM | db.Where() 链式调用 |
| Python / SQLAlchemy | session.query().filter() |
三、代码质量
适用场景:写新方法、重构老代码、Code Review 检查代码可读性
方法拆分(强烈建议)
- 方法保持简短(建议 ≤50 行),超长按步骤拆分为含义明确的私有方法
- 卫语句优先,尽早 return/throw,主逻辑扁平化
// ✅ 扁平 + 拆分
public Result process(Request req) {
validate(req); // 校验
Entity e = convert(req); // 转换
Entity s = save(e); // 持久化
return buildResult(s); // 组装响应
}
// ❌ 一个方法 200 行:校验+转换+保存+日志+权限混在一起
命名
- 语义化,见名知义。反例:
check(u, p),正例:validateUserCredentials(username, password)
注释
- 复杂逻辑注释为什么(非做什么)
- 公共方法编写接口文档注释(JavaDoc / JSDoc / Docstring)
- 禁止
i++; // i加1类废话注释
四、健壮性
适用场景:处理外部输入、写涉及钱/状态的业务、排查偶发 NullPointerException
判空
- 使用语言/框架提供的工具类统一判空:
- Java:
CollectionUtils.isEmpty(list)、StringUtils.isBlank(str) - C#:
string.IsNullOrWhiteSpace(str)、list?.Any() != true - Python:
if not list:、if not str.strip(): - Go:
if len(list) == 0
- Java:
- 方法返回空集合用
Collections.emptyList()或new ArrayList<>(),禁止 return null
入参校验
- Handler 层:使用框架校验机制(
@Valid/@Validated/ Pydantic / go-validator) - Service 层:关键参数二次校验(防非 Handler 调用)
事务
声明式事务必须显式指定回滚策略(rollbackFor 或等效配置)。
注意:只有跨代理的 public 方法调用才会触发事务,同类内部调用不走代理。
- 读操作不加事务或用只读事务
- 事务边界越小越好,避免长事务锁表
异常
适用场景:新写业务逻辑、排查线上报错缺少关键信息
| 类型 | 场景 |
|---|---|
| 业务异常(BusinessException) | 业务规则校验不通过 |
| 参数异常(IllegalArgumentException) | 参数非法 |
| 权限异常(ForbiddenException) | 权限/认证失败 |
| 系统异常(SystemException) | 数据库连接、外部服务不可用等 |
禁止:吞异常(catch{}空)、暴露内部细节(SQL 语句、堆栈放入异常消息)
幂等
适用场景:支付、审批、扣库存、表单提交——任何"不能重复执行"的操作
- 状态机校验(操作前检查当前状态)
- 乐观锁(version 字段)
- 唯一键约束(数据库层兜底)
- 幂等键(Idempotency-Key)去重
五、性能
适用场景:排查接口慢、数据量大了之后变卡、内存持续增长
| 陷阱 | 通用做法 |
|---|---|
| N+1 查询 | 批量查询,用 Map 分组关联 |
| O(n²) 嵌套循环 | 一侧转 Map<key, Entity>,另一侧 map.get(key) O(1) |
| 循环内创建格式化对象 | 提取为 static final 或复用实例 |
| Stream 滥用 | 不修改外部变量;不抛受检异常;无限流用 limit() |
| 无差别的深度复制 | 按需复制字段,避免全量 Clone |
六、日志
适用场景:排查线上问题却发现"啥也没打"、日志太多卡死磁盘、敏感信息泄露
统一日志框架(SLF4J / Log4j / Zap / logrus)。级别:
| 级别 | 用途 |
|---|---|
error |
需人工介入,必须携带异常对象 |
warn |
业务降级/数据异常 |
info |
关键业务节点 |
debug |
调试信息 |
log.info("操作成功, id={}, key={}", id, key); // ✅ 参数化占位符
log.info("操作成功, id=" + id); // ❌ 字符串拼接(提前求值开销)
- 禁止打印大对象、密码、Token
- 异常日志:
log.error("msg", e),缺少异常对象不打印堆栈
七、异步
适用场景:发邮件/短信/通知、批量处理耗时任务、用
@Async时发现 TraceId 丢了
- 使用统一的线程池(
ThreadPoolExecutor/TaskExecutor),禁止new Thread() - 根据任务类型使用不同线程池(IO 密集型 vs CPU 密集型)
- 异步任务独立处理异常(异步执行时调用栈已脱离)
- 注意上下文传递(RequestContext / TraceId 等需显式传递)
- 控制并发上限,防止线程池耗尽
八、SQL 安全
适用场景:写动态 SQL、前端传排序字段、需要拼接表名或列名
- 参数绑定(
?/#{}/$1):默认使用预编译防注入 - 动态字符串替换(
${}/ 字符串拼接):仅限动态表名/列名,必须经白名单校验 - 禁止
select *,显式列出所需字段 - 动态排序字段:必须服务端白名单校验,不通过则报参数错误
九、常量与配置
适用场景:代码里出现了
"admin"、1、"PENDING"这样的字符串/数字
// 硬编码 → 常量类
public class Constants {
public static final int STATUS_ACTIVE = 1;
}
// 可变配置 → 配置类(@ConfigurationProperties / @Value / config file)
@ConfigurationProperties(prefix = "app.feature")
public class FeatureConfig { ... }
- 禁止魔法值散落业务代码
十、设计模式原则
适用场景:if-else 超过 3 个分支、同一接口有多种实现、多个流程步骤固定但细节不同
- 策略模式:≥3 个 if-else 分支考虑策略类抽取
- 工厂模式:多种实现按类型创建时使用
- 模板方法:固定流程+可变步骤
- 但:简单 CRUD 别套模式,只有一种实现别建工厂
典型错误对照清单
Code Review 时按此清单逐项检查:
| # | 典型错误 | 正确做法 | 相关章节 |
|---|---|---|---|
| 1 | Controller 里写 SQL / 调 Mapper | 业务逻辑必须下沉到 Service | 分层职责 |
| 2 | Service 直接操作 HttpServletRequest |
需要的信息由 Controller 传入 | 分层职责 |
| 3 | return null 给列表 |
return Collections.emptyList() |
判空 |
| 4 | catch (Exception e) {} 空块 |
至少 log.error("xxx", e),然后视情况抛业务异常 |
异常 |
| 5 | log.error("失败: " + e.getMessage()) |
log.error("失败, orderId={}", orderId, e) —— 必须传异常对象 |
日志 |
| 6 | 循环里 mapper.selectById(id) |
收集 ID 列表,一次性 selectBatchIds(ids) |
性能 |
| 7 | new Thread(() -> {...}).start() |
注入 TaskExecutor,executor.execute(...) |
异步 |
| 8 | 动态排序 ORDER BY ${sortField} |
服务端白名单校验,不通过则拒绝 | SQL 安全 |
| 9 | if (status == 1) 魔法值 |
定义 ProcessStatusEnum 或常量 |
常量与配置 |
| 10 | @Transactional 不加 rollbackFor |
@Transactional(rollbackFor = Exception.class) |
事务 |
| 11 | 同类内 this.methodB() 期待事务 |
抽到独立 Service 或注入 self 代理 |
事务 |
| 12 | 返回集合时判空用 list == null |
用 CollectionUtils.isEmpty(list) |
判空 |
| 13 | 异步方法里用 RequestContextHolder |
显式传入 requestContext,在异步方法内 set | 异步 |
| 14 | 接口返回直接把 Entity 序列化 | 定义 VO/DTO,拷贝需要的字段返回 | 分层职责 |
常见问题速查(FAQ)
Q1: 我的 Service 方法越来越长(300+ 行),怎么拆?
先确认方法做了几件事:校验 → 查库 → 计算 → 写库 → 发通知?每一步提取为私有方法(如 validateOrder()、fetchRelated()、calculateAmount()、persistResult()),主方法只保留调用顺序。如果某些步骤可能复用,提取到独立的 Service。
Q2: @Transactional 怎么不生效?
三个常见原因:
- 同类调用:
this.doSomething()不经过 Spring AOP 代理 → 注入自身(@Autowired private XxxService self),通过self.doSomething()调用 - 异常类型不对:
rollbackFor没配,默认只回滚 RuntimeException → 加rollbackFor = Exception.class - 方法不是 public:AOP 只能代理 public 方法
Q3: 循环里逐条查库,现在数据多了很慢,怎么优化?
收集所有 ID → 批量查询 → 转 Map → 循环里 map.get(id)。这是一劳永逸的模式:
// ❌ N+1
for (Order o : orders) { User u = userMapper.selectById(o.getUserId()); }
// ✅ 批量 + Map
List<Long> userIds = orders.stream().map(Order::getUserId).distinct().collect(toList());
Map<Long, User> userMap = userMapper.selectBatchIds(userIds)
.stream().collect(toMap(User::getId, Function.identity()));
for (Order o : orders) { User u = userMap.get(o.getUserId()); }
Q4: 异步方法里 RequestContextHolder 拿不到当前用户了?
线程池的线程和请求线程不同,ThreadLocal 不会传递。解决:在主线程取出 context,作为参数传入异步方法,异步方法第一行手动 set。
Q5: 前端传排序字段,怎么防 SQL 注入?
服务端维护一个合法排序字段的白名单 Set:
private static final Set<String> ALLOWED_SORT_FIELDS = Set.of("id", "name", "createTime");
if (!ALLOWED_SORT_FIELDS.contains(sortField)) {
throw new IllegalArgumentException("不支持的排序字段: " + sortField);
}
Q6: 什么时候该用策略模式,什么时候不需要?
≥3 个 if-else 分支 + 每个分支有独立业务逻辑 → 策略模式。只有 2 个分支或只是简单赋值 → 不需要,if-else 更清晰。
Q7: 日志打太多/太少怎么办?
经验法则:
- 接口入口/出口各一条 info(含核心参数和结果)
- 调用外部服务/写库前后各一条 info
- catch 块里一条 error(必须带异常对象)
- debug 级别可随意,线上不开 debug 级别即可
实战案例:订单状态流转
下面是一个完整的从需求到代码的实现过程,展示以上规范如何落地。
需求
电商订单从"待支付"→"已支付"→"已发货"→"已完成",状态流转必须满足:
- 只能按顺序流转,不能跳过
- 已取消的订单不能操作
- 支付成功后发通知(异步)
- 接口幂等(重复请求不重复处理)
第一步:定义实体和枚举
// 枚举替代魔法值
public enum OrderStatus {
PENDING_PAY(0, "待支付"),
PAID(1, "已支付"),
SHIPPED(2, "已发货"),
COMPLETED(3, "已完成"),
CANCELLED(4, "已取消");
// 合法流转路径
static {
PENDING_PAY.next = Set.of(PAID, CANCELLED);
PAID.next = Set.of(SHIPPED);
SHIPPED.next = Set.of(COMPLETED);
}
Set<OrderStatus> next;
public boolean canTransitTo(OrderStatus target) {
return next != null && next.contains(target);
}
}
// Entity(只在 Service/Repository 层使用)
@Data
@TableName("t_order")
public class Order {
private Long id;
private Long userId;
private Integer status; // OrderStatus.code
private BigDecimal amount;
private Integer version; // 乐观锁
private LocalDateTime createTime;
}
第二步:Controller — 只管参数校验和响应
@RestController
@RequestMapping("/main/order")
public class OrderController {
@Autowired
private IOrderService orderService;
@PostMapping("/{id}/status")
public CommonResponse<Void> updateStatus(
@PathVariable Long id,
@RequestBody @Valid UpdateStatusReq req) {
orderService.transitStatus(id, req.getTargetStatus());
return CommonResponse.success("状态变更成功");
}
}
// 请求 DTO(与 Entity 隔离)
@Data
public class UpdateStatusReq {
@NotNull
private Integer targetStatus;
}
第三步:Service — 纯业务逻辑,零 Web 依赖
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {
@Autowired private OrderMapper orderMapper;
@Autowired private TaskExecutor taskExecutor; // 线程池,不 new Thread
@Override
@Transactional(rollbackFor = Exception.class) // ← 必须 rollbackFor
public void transitStatus(Long orderId, Integer targetStatusCode) {
// 1. 业务校验
OrderStatus current = getCurrentStatus(orderId);
OrderStatus target = OrderStatus.fromCode(targetStatusCode);
if (!current.canTransitTo(target)) {
throw new BusinessException(
String.format("不允许从 %s 变更为 %s", current.getDesc(), target.getDesc()));
}
// 2. 乐观锁更新(幂等 + 并发安全)
int rows = orderMapper.updateStatusCas(
orderId, current.getCode(), target.getCode(), current.getVersion());
if (rows == 0) {
throw new BusinessException("状态已变更,请刷新后重试");
}
// 3. 异步通知(不阻塞主流程,独立异常处理)
if (target == OrderStatus.PAID) {
taskExecutor.execute(() -> {
try {
notifyPaymentSuccess(orderId);
} catch (Exception e) {
log.error("支付通知失败, orderId={}", orderId, e); // ← 带异常对象
}
});
}
log.info("订单状态变更成功, orderId={}, {} → {}", orderId, current.getDesc(), target.getDesc());
}
private Order getCurrentStatus(Long orderId) {
Order order = orderMapper.selectById(orderId);
if (order == null || CollectionUtils.isEmpty(order)) { // ← 统一判空
throw new BusinessException("订单不存在");
}
return order;
}
// 私有方法封装,保持主方法整洁
private void notifyPaymentSuccess(Long orderId) {
// 发短信/消息队列等
}
}
第四步:Repository — 纯数据操作
@Mapper
public interface OrderMapper extends BaseMapper<Order> {
// CAS 更新,version 做乐观锁
@Update("UPDATE t_order SET status = #{targetStatus}, version = version + 1 " +
"WHERE id = #{id} AND status = #{currentStatus} AND version = #{version}")
int updateStatusCas(@Param("id") Long id,
@Param("currentStatus") Integer currentStatus,
@Param("targetStatus") Integer targetStatus,
@Param("version") Integer version);
// 批量查询
List<Order> selectByUserIds(@Param("userIds") List<Long> userIds);
}
回头看:这个案例用到了哪些规范
| 规范 | 体现位置 |
|---|---|
| 分层职责 | Controller 只管参数 → Service 管业务 → Mapper 管数据 |
| 枚举代替魔法值 | OrderStatus 枚举 + canTransitTo() 状态机 |
| 异常分类 | BusinessException 区分业务 vs 系统异常 |
| 幂等 | CAS 更新 + 状态机校验,重复请求返回友好提示 |
| 事务配置 | @Transactional(rollbackFor = Exception.class) |
| 异步 | 注入 TaskExecutor,独立的 try-catch |
| 日志规范 | 关键节点 info,异常带对象,参数化占位 |
| 判空统一 | CollectionUtils.isEmpty(order) |
| Entity/DTO 隔离 | 请求用 UpdateStatusReq,存储用 Order |
进阶技巧
1. 防御性编程:永远假设外部数据不可信
// ❌ 假设 response 一定有数据
UserDto user = thirdPartyClient.getUser(id);
String name = user.getName(); // user 为 null → NPE
// ✅ 防御
UserDto user = thirdPartyClient.getUser(id);
if (user == null) {
throw new SystemException("第三方用户查询为空, userId=" + id);
}
String name = ObjectUtil.defaultIfNull(user.getName(), "未知");
2. 状态机模式替代 if-else 链
当状态流转超过 5 种状态、10 条规则时,考虑引入状态机(如 Spring Statemachine 或自建 transition map),将状态规则与业务逻辑解耦。
3. 批量操作按页切片
// ❌ 一次更新 10w 条,长事务锁表
mapper.batchUpdate(allRecords);
// ✅ 按 500 条一批,分批提交
List<Record> batch;
while (!(batch = takeNextBatch(records, 500)).isEmpty()) {
mapper.batchUpdate(batch);
}
4. 缓存穿透/击穿/雪崩三件套
- 穿透(查不存在的 key)→ 布隆过滤器 或 缓存空值(短 TTL)
- 击穿(热点 key 过期)→ 互斥锁 / 永不过期 + 异步刷新
- 雪崩(大量 key 同时过期)→ TTL 加随机值
严禁清单
- 方法过长(单方法一个屏幕无法完整阅读)| 嵌套循环 ≥4 层 | 硬编码魔法值
catch (Exception e) {}吞异常 |return null(集合类)- Handler/Controller 写业务逻辑 |
new Thread()| 日志字符串拼接 select *| 循环内逐条查库 | 动态 SQL(表名/列名/排序字段)不经白名单校验
Current listing version
1.0.1
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供全面的高质量工程编码设计规范,涵盖架构原则、代码质量、性能优化等关键领域
- 包含详细的实战案例和常见问题速查,具有很强的实用性和指导价值
- 适用于代码编写、重构、审查等多种场景,受众广泛
Highlights
- description清晰准确地描述了Skill的核心功能和适用场景
- skill_body内提供了详细的使用场景表格,帮助用户快速定位所需内容
- 触发词覆盖全面,边界清晰,不易产生误触或漏触
Areas to improve
-
文档过长 Reported severity: Minor
文档内容非常详细,但整体长度超过500行,可能影响阅读体验
Recommendation: 考虑将部分内容拆分为独立的子文档或提供更多折叠/展开功能
Highlights
- 文档结构清晰,分章节明确,逻辑性强
- 包含完整的实战案例和FAQ,增强了实用性
- frontmatter完整,符合规范要求
Highlights
- 提供了大量可执行的代码示例和最佳实践
- 内容基于行业标准和通用规范,具有高度可靠性
- 涵盖了异常处理、事务管理、性能优化等关键可靠性要素
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
These common operations were not identified in the main document. This does not mean no permissions or risks exist.
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.