8.3 团队协作与代码规范
AI时代的团队协作
角色重新定义
传统团队结构:
项目经理 → 技术负责人 → 开发者 → 实习生
问题:
- 层级过多,沟通效率低
- 信息传递失真
- 决策周期长AI时代团队结构:
产品负责人 (Product Owner)
├─ 需求定义
└─ 优先级排序
技术架构师 (Tech Lead)
├─ 技术决策
├─ 代码审查
└─ 团队指导
全栈开发者 (2-3人)
├─ AI协作开发
├─ 端到端交付
└─ 持续学习
运维工程师 (DevOps)
├─ CI/CD 流水线
├─ 监控告警
└─ 自动化部署AI辅助角色
AI作为团队成员:
角色:AI 代码助手 (Claude/Cursor/GitHub Copilot)
职责:
1. 代码生成
- 根据需求生成代码
- 提供多种实现方案
- 解释复杂逻辑
2. 代码审查
- 检查代码质量
- 发现潜在问题
- 提出改进建议
3. 文档生成
- 自动生成API文档
- 编写技术文档
- 创建用户手册
4. 测试编写
- 生成单元测试
- 提供测试用例
- 检查测试覆盖率代码规范体系
代码风格指南
JavaScript/TypeScript 规范:
// ✅ 命名规范
const MAX_RETRY_COUNT = 3 // 常量:全大写+下划线
let userName = 'John' // 变量:camelCase
function calculateTotal() { } // 函数:camelCase
class UserService { } // 类:PascalCase
const API_URL = '/api/users' // 配置:大写+下划线
// ✅ 函数设计
// 单个职责
async function getUserById(id) {
return await db.users.findUnique({ where: { id } })
}
// 清晰参数
function createUser({ name, email, role }) {
// ...
}
// ✅ 错误处理
try {
const user = await getUserById(id)
if (!user) throw new Error('User not found')
return user
} catch (error) {
logger.error('Failed to get user', { id, error })
throw error
}
// ✅ 注释规范
/**
* 获取用户信息
* @param {string} id - 用户ID
* @param {Object} options - 选项
* @param {boolean} options.includeProfile - 是否包含详细信息
* @returns {Promise<Object>} 用户信息
* @throws {Error} 用户不存在时抛出
*/
async function getUser(id, { includeProfile = false } = {}) {
// ...
}Git 提交规范
Conventional Commits:
# 格式
<type>[optional scope]: <description>
# 示例
feat: 添加用户登录功能
fix: 修复密码重置bug
docs: 更新API文档
style: 代码格式化
refactor: 重构用户服务
test: 添加单元测试
chore: 更新依赖版本
# 详细格式
feat(auth): 添加OAuth2.0登录支持
- 实现Google OAuth登录
- 实现GitHub OAuth登录
- 添加用户会话管理
- 更新登录页面UI
Closes #123提交模板:
# .gitmessage
[类型]: 简短描述
详细描述(可选)
影响范围:
- 用户系统
- 支付系统
Breaking Changes:
- 移除了旧的API v1
相关Issue:
Closes #123
Refs #456代码审查 (Code Review)
审查清单:
## 功能性
- [ ] 代码实现了需求
- [ ] 没有隐藏的bug
- [ ] 边界条件处理正确
- [ ] 错误处理完善
## 代码质量
- [ ] 代码清晰易读
- [ ] 命名有意义
- [ ] 函数职责单一
- [ ] 没有重复代码
- [ ] 注释充分且准确
## 性能
- [ ] 数据库查询优化
- [ ] 没有N+1查询
- [ ] 图片懒加载
- [ ] API响应时间合理
## 安全
- [ ] 用户输入验证
- [ ] SQL注入防护
- [ ] 敏感信息不暴露
- [ ] 权限检查完善
## 测试
- [ ] 单元测试覆盖
- [ ] 集成测试覆盖
- [ ] 测试用例合理
- [ ] 测试通过
## 文档
- [ ] API文档更新
- [ ] README更新
- [ ] 复杂逻辑有注释审查反馈模板:
## ✅ 需要修改 (Blocking)
这段代码有严重问题:
```javascript
// 问题:SQL注入风险
const users = await db.query(`SELECT * FROM users WHERE id = ${userId}`)建议修改:
// 使用参数化查询
const users = await db.users.findUnique({ where: { id: userId } })💡 建议改进 (Non-blocking)
可以考虑这样优化:
// 当前实现
const user = await getUserById(id)
// 建议
const user = await getUserById(id, {
includeProfile: true,
cache: true
})这样可以减少后续API调用。
👍 看起来不错 (Non-blocking)
代码质量很好!简洁清晰,错误处理到位。
## CI/CD 流水线
### GitHub Actions 工作流
**基础CI/CD配置**:
```yaml
# .github/workflows/ci.yml
name: CI/CD Pipeline
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run linting
run: npm run lint
- name: Run type checking
run: npm run type-check
- name: Run unit tests
run: npm run test
- name: Run integration tests
run: npm run test:integration
- name: Upload coverage
uses: codecov/codecov-action@v3
deploy:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v4
- name: Deploy to Vercel
uses: amondnet/vercel-action@v25
with:
vercel-token: ${{ secrets.VERCEL_TOKEN }}
vercel-org-id: ${{ secrets.ORG_ID }}
vercel-project-id: ${{ secrets.PROJECT_ID }}自动化测试策略
测试金字塔:
E2E Tests (10)
/ \
/ \
Integration (20) UI Tests
/ \ / \
Unit (70) API Tests Manual Testing测试配置:
// jest.config.ts
export default {
testEnvironment: 'jest-environment-jsdom',
setupFilesAfterEnv: ['<rootDir>/src/test/setup.ts'],
testMatch: [
'<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}',
'<rootDir>/src/**/*.{test,spec}.{js,jsx,ts,tsx}'
],
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80
}
}
}
// 测试示例
describe('UserService', () => {
describe('getUserById', () => {
it('should return user when valid id provided', async () => {
// Arrange
const mockUser = { id: '1', name: 'John' }
jest.spyOn(db.users, 'findUnique')
.mockResolvedValue(mockUser)
// Act
const result = await userService.getUserById('1')
// Assert
expect(result).toEqual(mockUser)
expect(db.users.findUnique).toHaveBeenCalledWith({
where: { id: '1' }
})
})
it('should throw error when user not found', async () => {
// Arrange
jest.spyOn(db.users, 'findUnique')
.mockResolvedValue(null)
// Act & Assert
await expect(userService.getUserById('999'))
.rejects
.toThrow('User not found')
})
})
})文档规范
技术文档结构
docs/
├── README.md # 项目概览
├── CONTRIBUTING.md # 贡献指南
├── ARCHITECTURE.md # 架构设计
├── API.md # API文档
├── DEPLOYMENT.md # 部署指南
├── DEVELOPMENT.md # 开发指南
└── wiki/
├── feature-1/
└── feature-2/README模板:
# Project Name
Brief description of the project.
## 🚀 Quick Start
```bash
# Install dependencies
npm install
# Setup environment
cp .env.example .env
# Start development server
npm run dev📋 Prerequisites
- Node.js 18+
- PostgreSQL 14+
- Redis 6+
🏗️ Architecture
High-level architecture diagram…
📚 API Documentation
🧪 Testing
npm run test # Unit tests
npm run test:e2e # End-to-end tests
npm run test:coverage # Coverage report📦 Deployment
See DEPLOYMENT.md for detailed instructions.
👥 Team
- John Doe - Tech Lead
- Jane Smith - Frontend Developer
### API文档生成
**使用Swagger/OpenAPI**:
```typescript
// api/users/route.ts
import { NextRequest, NextResponse } from 'next/server'
/**
* @swagger
* /api/users:
* get:
* summary: 获取用户列表
* tags: [Users]
* parameters:
* - in: query
* name: page
* schema:
* type: integer
* default: 1
* description: 页码
* responses:
* 200:
* description: 用户列表
* content:
* application/json:
* schema:
* type: object
* properties:
* data:
* type: array
* items:
* $ref: '#/components/schemas/User'
* pagination:
* $ref: '#/components/schemas/Pagination'
*/
export async function GET(request: NextRequest) {
// Implementation
}知识管理
知识库结构
knowledge-base/
├── best-practices/
│ ├── coding-standards.md
│ ├── api-design.md
│ └── database-design.md
├── learnings/
│ ├── lessons-learned.md
│ ├── pitfall-cases.md
│ └── success-stories.md
├── processes/
│ ├── onboarding.md
│ ├── code-review.md
│ └── deployment.md
└── resources/
├── tools.md
├── libraries.md
└── external-links.md技术分享会
月度技术分享:
频率:每月第2个周三
时长:1小时
参与者:全团队
议程:
1. 新技术分享 (20分钟)
- 近期学习的新技术
- 实际项目中的应用
2. 项目复盘 (20分钟)
- 成功案例分享
- 问题分析和解决
3. 改进提案 (20分钟)
- 流程改进建议
- 工具推荐
- 最佳实践
会后行动:
- 整理笔记到知识库
- 分配改进任务
- 跟踪实施进度团队沟通
异步沟通原则
文档优先:
讨论问题 → 先查文档
找不到文档 → 补充文档
文档过时 → 更新文档沟通渠道:
Slack / 微信群
├─ 日常沟通
├─ 快速问题
└─ 临时讨论
GitHub Issues
├─ Bug报告
├─ 功能需求
└─ 技术讨论
文档库 (Notion/Confluence)
├─ 正式决策
├─ 流程规范
└─ 知识沉淀会议管理
会议类型:
每日站会 (Daily Standup)
├─ 时长:15分钟
├─ 内容:昨天完成/今天计划/遇到问题
└─ 工具:Slack/Zoom
周会 (Weekly Meeting)
├─ 时长:1小时
├─ 内容:进度同步/问题讨论/下周计划
└─ 工具:Google Meet
季度回顾 (Quarterly Retrospective)
├─ 时长:3小时
├─ 内容:成果回顾/问题分析/改进计划
└─ 工具:线下会议会议准备:
会前:
- 提前发送议程
- 准备相关文档
- 明确会议目标
会中:
- 记录关键决策
- 记录行动项
- 控制时间
会后:
- 24小时内发送会议纪要
- 分配行动项
- 跟踪执行进度代码质量管理
自动化检查
Pre-commit Hooks:
# .husky/pre-commit
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npm run lint
npm run type-check
npm run test
npm run test:e2eESLint配置:
{
"extends": [
"next/core-web-vitals",
"@typescript-eslint/recommended",
"prettier"
],
"rules": {
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/no-explicit-any": "warn",
"prefer-const": "error",
"no-console": "warn"
}
}SonarQube 质量门禁
# sonar-project.properties
sonar.projectKey=my-project
sonar.sources=src
sonar.tests=src
sonar.test.inclusions=**/*.test.ts,**/*.spec.ts
sonar.coverage.exclusions=**/*.test.ts,**/*.spec.ts
sonar.issue.ignore.multicriteria=e1
sonar.issue.ignore.multicriteria.e1.ruleKey=javascript:S1192
sonar.issue.ignore.multicriteria.e1.resourceKey=**/*.ts最佳实践总结
新人入职清单
第1天:
- [ ] 配置开发环境
- [ ] 访问代码仓库
- [ ] 阅读项目文档
- [ ] 了解团队成员
第1周:
- [ ] 运行项目本地环境
- [ ] 完成第一个简单任务
- [ ] 参与代码审查
- [ ] 熟悉Git流程
第1个月:
- [ ] 独立开发完整功能
- [ ] 参与技术分享
- [ ] 提出改进建议
- [ ] 熟悉部署流程代码规范检查表
提交前自检:
□ 代码格式正确 (Prettier)
□ 没有ESLint错误
□ TypeScript类型检查通过
□ 单元测试全部通过
□ 测试覆盖率达标
□ 提交信息符合规范
□ 相关文档已更新
□ 本地构建成功
□ 没有console.log调试信息记住:规范的目的是提高效率,而不是增加负担。自动化能自动化的,保持人性化的沟通。
Last updated on