
Clean Code Reviewer
- 12 installs
- 53 repo stars
- Updated January 10, 2026
- hylarucoder/skills-for-vibe-coder
Reviews code against Clean Code principles for naming, function size, duplication, over-engineering, and magic numbers with severity ratings and refactor suggestions.
About
Analyzes code quality across seven Clean Code dimensions and reports issues sorted by severity. A developer uses it for a code review, quality check, or code-smell detection while preserving functionality.
- Seven high-value checks: naming, functions, DRY, YAGNI, magic numbers, clarity, conventions
- Suggestions only change implementation, never behavior
Clean Code Reviewer by the numbers
- 12 all-time installs (skills.sh)
- Ranked #798 of 1,352 Code Review & Quality skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/hylarucoder/skills-for-vibe-coder --skill clean-code-reviewerAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 12 |
|---|---|
| repo stars | ★ 53 |
| Last updated | January 10, 2026 |
| Repository | hylarucoder/skills-for-vibe-coder ↗ |
What it does
Reviews code against Clean Code principles for naming, function size, duplication, over-engineering, and magic numbers with severity ratings and refactor suggestions.
Files
Clean Code Review
基于《代码整洁之道》原则,聚焦 7 个高收益检查维度。
Review Workflow
Review Progress:
- [ ] 1. Scan codebase: identify files to review
- [ ] 2. Check each dimension (naming, functions, DRY, YAGNI, magic numbers, clarity, conventions)
- [ ] 3. Rate severity (高/中/低) for each issue
- [ ] 4. Generate report sorted by severity核心原则:功能保留
所有建议仅针对实现方式优化——绝不建议改变代码的功能、输出或行为。
Check Dimensions
1. 命名问题【有意义的命名】
检查标志:
data1,temp,result,info,obj等无意义命名- 同一概念多种命名(
get/fetch/retrieve混用)
// ❌
const d = new Date();
const data1 = fetchUser();
// ✅
const currentDate = new Date();
const userProfile = fetchUser();2. 函数问题【函数短小 + SRP】
检查标志:
- 函数超过 100 行
- 参数超过 3 个
- 函数做多件事
// ❌ 7 个参数
function processOrder(user, items, address, payment, discount, coupon, notes)
// ✅ 使用参数对象
interface OrderParams { user: User; items: Item[]; shipping: Address; payment: Payment }
function processOrder(params: OrderParams)3. 重复问题【DRY】
检查标志:
- 相似的 if-else 结构
- 相似的数据转换/错误处理逻辑
- Copy-paste 痕迹
4. 过度设计【YAGNI】
检查标志:
- 从未为 true 的
if (config.legacyMode)分支 - 只有一个实现的接口
- 无用的 try-catch 或 if-else
// ❌ YAGNI 违反:从未使用的兼容代码
if (config.legacyMode) {
// 100 行兼容代码
}5. 魔法数字【避免硬编码】
检查标志:
- 裸露数字无解释
- 硬编码字符串
// ❌
if (retryCount > 3) // 3 是什么?
setTimeout(fn, 86400000) // 这是多久?
// ✅
const MAX_RETRY_COUNT = 3;
const ONE_DAY_MS = 24 * 60 * 60 * 1000;6. 结构清晰度【可读性优先】
检查标志:
- 嵌套三元运算符
- 过度紧凑的单行代码
- 过深的条件嵌套(> 3 层)
// ❌ 嵌套三元
const status = a ? (b ? 'x' : 'y') : (c ? 'z' : 'w');
// ✅ 使用 switch 或 if/else
function getStatus(a, b, c) {
if (a) return b ? 'x' : 'y';
return c ? 'z' : 'w';
}7. 项目规范【一致性】
检查标志:
- import 顺序混乱(外部库 vs 内部模块)
- 函数声明风格不一致
- 命名规范不统一(camelCase vs snake_case 混用)
// ❌ 风格不一致
import { api } from './api'
import axios from 'axios' // 外部库应在前
const handle_click = () => { ... } // 命名风格混用
// ✅ 统一风格
import axios from 'axios'
import { api } from './api'
function handleClick(): void { ... }[!TIP]
项目规范应参照CLAUDE.mdAGENTS.md或项目约定的编码标准。
Severity Levels
| 级别 | 标准 |
|---|---|
| 高 | 影响可维护性/可读性,应立即修复 |
| 中 | 有改进空间,建议修复 |
| 低 | 代码气味,可选优化 |
Output Format
### [问题类型]: [简述]
- **原则**: [Clean Code 原则]
- **位置**: `文件:行号`
- **级别**: 高/中/低
- **问题**: [具体描述]
- **建议**: [修复方向]References
Detailed examples: See references/detailed-examples.md
- 各维度的完整案例(命名、函数、DRY、YAGNI、魔法数字)
Language patterns: See references/language-patterns.md
- TypeScript/JavaScript 常见问题
- Python 常见问题
- Go 常见问题
Multi-Agent Parallel
按以下维度拆分给多 agent 并行:
1. 按检查维度 - 7 维度各一个 agent 2. 按模块/目录 - 不同模块各一个 agent 3. 按语言 - TypeScript、Python、Go 各一个 agent 4. 按文件类型 - 组件、hooks、工具函数、类型定义
示例:/clean-code-reviewer --scope=components 或 --dimension=naming
汇总时需去重和统一严重程度评定。
Detailed Examples by Dimension
Table of Contents
---
1. 命名问题
无意义命名
// ❌
const list = getUsers(); // list of what?
const flag = checkPermission(); // what flag?
const handler = () => {}; // handles what?
// ✅
const activeUsers = getUsers();
const hasEditPermission = checkPermission();
const onFormSubmit = () => {};命名不一致
// ❌ 同一概念多种命名
getUserData();
fetchUserInfo();
retrieveUserProfile();
// ✅ 统一使用一种
getUser();
getUserProfile();
getUserSettings();布尔命名
// ❌
const open = true;
const disabled = false;
// ✅ 带 is/has/can/should 前缀
const isOpen = true;
const isDisabled = false;
const hasPermission = true;
const canEdit = true;---
2. 函数问题
函数过长
// ❌ 160 行的 processOrder 函数
async function processOrder(order) {
// 验证逻辑 (40 行)
// 计算逻辑 (30 行)
// 库存检查 (25 行)
// 支付处理 (35 行)
// 通知发送 (30 行)
}
// ✅ 拆分为单一职责函数
async function processOrder(order) {
await validateOrder(order);
const total = calculateTotal(order);
await checkInventory(order.items);
await processPayment(order, total);
await sendNotifications(order);
}参数过多
// ❌
function createUser(name, email, age, address, phone, role, department, manager) {}
// ✅ 使用配置对象
interface CreateUserParams {
name: string;
email: string;
profile: { age: number; phone: string };
organization: { role: string; department: string; manager: string };
}
function createUser(params: CreateUserParams) {}副作用
// ❌ 函数名暗示只读,但有副作用
function getUser(id) {
const user = db.find(id);
user.lastAccess = new Date(); // 副作用!
db.save(user); // 副作用!
return user;
}
// ✅ 分离读写
function getUser(id) {
return db.find(id);
}
function recordUserAccess(id) {
const user = db.find(id);
user.lastAccess = new Date();
db.save(user);
}---
3. 重复问题
相似的验证逻辑
// ❌ 重复的验证模式
function validateUser(user) {
if (!user.name) throw new Error('Name required');
if (!user.email) throw new Error('Email required');
if (!user.age) throw new Error('Age required');
}
function validateProduct(product) {
if (!product.name) throw new Error('Name required');
if (!product.price) throw new Error('Price required');
if (!product.sku) throw new Error('SKU required');
}
// ✅ 提取通用验证器
function validateRequired(obj, fields) {
for (const field of fields) {
if (!obj[field]) throw new Error(`${field} required`);
}
}
validateRequired(user, ['name', 'email', 'age']);
validateRequired(product, ['name', 'price', 'sku']);相似的错误处理
// ❌ 重复的 try-catch 模式
async function fetchUsers() {
try {
return await api.get('/users');
} catch (e) {
logger.error('Failed to fetch users', e);
throw new ApiError('Failed to fetch users');
}
}
async function fetchProducts() {
try {
return await api.get('/products');
} catch (e) {
logger.error('Failed to fetch products', e);
throw new ApiError('Failed to fetch products');
}
}
// ✅ 提取通用包装器
async function apiCall(endpoint, errorMessage) {
try {
return await api.get(endpoint);
} catch (e) {
logger.error(errorMessage, e);
throw new ApiError(errorMessage);
}
}
const users = await apiCall('/users', 'Failed to fetch users');
const products = await apiCall('/products', 'Failed to fetch products');---
4. 过度设计
无用的抽象层
// ❌ 只有一个实现的接口
interface IUserRepository {
findById(id: string): User;
}
class UserRepository implements IUserRepository {
findById(id: string): User { /* ... */ }
}
// ✅ 直接使用类,需要时再抽象
class UserRepository {
findById(id: string): User { /* ... */ }
}过度防御
// ❌ 过度防御的代码
function add(a, b) {
if (typeof a !== 'number') throw new Error('a must be number');
if (typeof b !== 'number') throw new Error('b must be number');
if (isNaN(a)) throw new Error('a is NaN');
if (isNaN(b)) throw new Error('b is NaN');
if (!isFinite(a)) throw new Error('a is not finite');
if (!isFinite(b)) throw new Error('b is not finite');
return a + b;
}
// ✅ 合理的类型安全 (TypeScript)
function add(a: number, b: number): number {
return a + b;
}从未使用的配置
// ❌
if (config.enableNewFeature) { // 一直是 true
newFeature();
} else {
oldFeature(); // 死代码
}
// ✅ 删除死代码
newFeature();---
5. 魔法数字
业务逻辑中的数字
// ❌
if (user.age >= 18) {}
if (order.total > 100) {}
if (retryCount < 3) {}
// ✅
const LEGAL_AGE = 18;
const FREE_SHIPPING_THRESHOLD = 100;
const MAX_RETRY_ATTEMPTS = 3;
if (user.age >= LEGAL_AGE) {}
if (order.total > FREE_SHIPPING_THRESHOLD) {}
if (retryCount < MAX_RETRY_ATTEMPTS) {}时间常量
// ❌
setTimeout(fn, 86400000); // 这是多久?
setInterval(poll, 300000); // 这是多久?
// ✅
const ONE_DAY_MS = 24 * 60 * 60 * 1000;
const FIVE_MINUTES_MS = 5 * 60 * 1000;
setTimeout(fn, ONE_DAY_MS);
setInterval(poll, FIVE_MINUTES_MS);HTTP 状态码
// ❌
if (response.status === 200) {}
if (response.status === 404) {}
// ✅
const HTTP_OK = 200;
const HTTP_NOT_FOUND = 404;
// 或使用常量库: import { StatusCodes } from 'http-status-codes';Language-Specific Patterns
Table of Contents
---
TypeScript/JavaScript
any 类型滥用
// ❌
function process(data: any) {
return data.value;
}
// ✅
interface DataPayload {
value: string;
}
function process(data: DataPayload) {
return data.value;
}回调地狱
// ❌
getUser(id, (user) => {
getOrders(user.id, (orders) => {
processOrders(orders, (result) => {
sendNotification(result, () => {
console.log('done');
});
});
});
});
// ✅
const user = await getUser(id);
const orders = await getOrders(user.id);
const result = await processOrders(orders);
await sendNotification(result);可选链缺失
// ❌
if (user && user.profile && user.profile.address && user.profile.address.city) {}
// ✅
if (user?.profile?.address?.city) {}解构赋值
// ❌
const name = user.name;
const email = user.email;
const age = user.age;
// ✅
const { name, email, age } = user;---
Python
列表推导滥用
# ❌ 过于复杂的列表推导
result = [x.value for x in items if x.is_valid and x.type == 'A' for y in x.children if y.active]
# ✅ 拆分为函数
def get_active_children(items):
for item in items:
if item.is_valid and item.type == 'A':
for child in item.children:
if child.active:
yield child.value
result = list(get_active_children(items))可变默认参数
# ❌ 危险!可变对象作为默认参数
def add_item(item, items=[]):
items.append(item)
return items
# ✅
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items裸 except
# ❌
try:
risky_operation()
except:
pass
# ✅
try:
risky_operation()
except SpecificError as e:
logger.warning(f"Operation failed: {e}")字符串拼接
# ❌
message = "Hello " + name + "! You have " + str(count) + " messages."
# ✅
message = f"Hello {name}! You have {count} messages."类型提示缺失
# ❌
def process(data):
return data['value']
# ✅
from typing import TypedDict
class DataPayload(TypedDict):
value: str
def process(data: DataPayload) -> str:
return data['value']---
Go
忽略错误
// ❌
result, _ := someFunction()
// ✅
result, err := someFunction()
if err != nil {
return fmt.Errorf("someFunction failed: %w", err)
}过长的 init 函数
// ❌ init() 做太多事
func init() {
// 数据库连接
// 配置加载
// 缓存初始化
// 日志设置
// 100+ 行...
}
// ✅ 拆分职责
func init() {
initConfig()
initLogger()
}
func main() {
db := initDatabase()
cache := initCache()
// ...
}空接口滥用
// ❌
func process(data interface{}) {
v := data.(map[string]interface{})
// ...
}
// ✅
type Payload struct {
Value string `json:"value"`
}
func process(data Payload) {
// 类型安全
}过深嵌套
// ❌
func process(order *Order) error {
if order != nil {
if order.Items != nil {
if len(order.Items) > 0 {
for _, item := range order.Items {
if item.Valid {
// 实际逻辑
}
}
}
}
}
return nil
}
// ✅ 早返回 (Guard Clauses)
func process(order *Order) error {
if order == nil {
return nil
}
if order.Items == nil || len(order.Items) == 0 {
return nil
}
for _, item := range order.Items {
if !item.Valid {
continue
}
// 实际逻辑
}
return nil
}context 滥用
// ❌ 用 context 传业务数据
ctx = context.WithValue(ctx, "user", user)
ctx = context.WithValue(ctx, "order", order)
// ✅ context 只用于取消和超时,业务数据显式传递
func processOrder(ctx context.Context, user User, order Order) error {
// ...
}