Skip to main content

代码搜索与导航

在大型项目中快速定位代码、理解代码关系是开发者的核心需求。传统IDE需要记大量快捷键、用多个搜索面板、频繁切换文件窗口。而Claude Code通过自然语言就能完成所有代码搜索和导航任务,让你专注于理解代码逻辑本身,而不是记忆复杂的操作命令。

搜索代码片段

基础文本搜索

最简单的搜索方式就是用自然语言描述你想找的内容:

在整个项目中搜索"handleError"

Claude Code会自动使用ripgrep(rg)进行高效搜索:

🔍 Searching for "handleError" in project...

Found 23 occurrences in 8 files:

📄 src/controllers/UserController.js
Line 45: handleError(error, res)
Line 89: handleError(error, res)
Line 134: handleError(error, res)

📄 src/controllers/PostController.js
Line 23: handleError(error, res)
Line 67: handleError(error, res)

📄 src/middleware/errorHandler.js
Line 12: function handleError(error, req, res, next) {
Line 15-18: Definition of handleError function

📄 src/utils/api.js
Line 78: handleError(err)

... (4 more files)

Would you like me to:
1. Show the handleError function definition
2. Find all usages of handleError
3. Analyze the error handling pattern

智能上下文搜索

Claude Code理解代码语义,可以进行智能搜索:

找到所有处理用户登录失败的代码

Claude Code会分析代码逻辑而不只是文本:

🔍 Semantic search for "login failure handling"...

Found 3 relevant code sections:

1. src/controllers/AuthController.js (lines 45-67)
```javascript
if (!user) {
logger.warn('Login attempt with non-existent user', { email });
return res.status(401).json({
error: 'Invalid credentials',
code: 'AUTH_FAILED'
});
}
  1. src/middleware/auth.js (lines 23-45)

    // Token validation failure
    if (!token) {
    return res.status(401).json({
    error: 'Authentication required',
    code: 'NO_TOKEN'
    });
    }
  2. src/services/loginService.js (lines 89-112)

    // Password mismatch handling
    const isValid = await bcrypt.compare(password, user.password);
    if (!isValid) {
    logger.warn('Invalid password attempt', { userId: user.id });
    throw new AuthenticationError('Invalid credentials');
    }

Pattern detected: 401 status codes + error logging + warning logs


### 对比传统方式

**传统IDE方式:**
1. 按 `Ctrl+Shift+F` 打开全局搜索
2. 输入搜索关键词
3. 在结果列表中逐个点击查看
4. 需要自己判断哪些结果相关
5. 手动跳转到每个文件

**Claude Code方式:**

找出所有可能导致内存泄漏的代码模式


Claude Code会:
- 理解"内存泄漏"的代码特征
- 搜索未清理的事件监听器、定时器、闭包等
- 提供详细分析和修复建议
- 标注风险等级

## 查找函数定义

### 快速定位定义

想知道某个函数在哪里定义:

找到sendEmail函数的定义


Claude Code会精确定位:

````text
📍 Function Definition: sendEmail

📄 src/services/emailService.js (lines 45-89)

```javascript
/**
* 发送邮件
* @param {Object} options - 邮件选项
* @param {string} options.to - 收件人邮箱
* @param {string} options.subject - 邮件主题
* @param {string} options.html - HTML内容
* @param {string} options.text - 纯文本内容(可选)
* @returns {Promise[Object]} 发送结果
*/
async sendEmail({ to, subject, html, text }) {
try {
// 验证邮箱格式
if (!this.isValidEmail(to)) {
throw new Error('Invalid email address');
}

// 构建邮件选项
const mailOptions = {
from: process.env.EMAIL_FROM,
to,
subject,
html,
text: text || this.htmlToText(html)
};

// 发送邮件
const info = await this.transporter.sendMail(mailOptions);

// 记录日志
logger.info('Email sent successfully', {
messageId: info.messageId,
to,
subject
});

return info;
} catch (error) {
logger.error('Failed to send email', {
error: error.message,
to,
subject
});
throw new EmailServiceError('Failed to send email', error);
}
}

Metadata:

  • File: src/services/emailService.js
  • Class: EmailService
  • Exported as: module.exports (singleton)
  • Dependencies: nodemailer, logger
  • Error handling: Yes (try-catch + custom error)
  • Lines of code: 45

### 智能跳转

Claude Code可以理解不同的引用方式:

```
跳转到AuthService的login方法
```

即使引用方式不同,也能准确定位:

```
🔍 Found multiple references to "AuthService.login":

1. Direct import:
src/routes/authRoutes.js
Line 12: const { login } = require('./services/AuthService');

2. Destructured from class:
src/controllers/AuthController.js
Line 5: const { login } = AuthService;

3. Method call:
src/tests/auth.test.js
Line 45: await AuthService.login(email, password);

📍 Definition location:
📄 src/services/AuthService.js (lines 23-67)

```javascript
static async login(email, password) {
// ... implementation
}
```

Would you like me to:
1. Show the full implementation
2. Find all usages of this method
3. Analyze the method's complexity
```

### 链式定义查找

当调用链很长时,Claude Code可以追踪完整链路:

```
追踪userProfile从API到数据库的完整调用链
```

Claude Code会构建完整的调用图:

```
🔗 Call Chain Analysis: userProfile

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📍 Entry Point: API Route
📄 src/routes/userRoutes.js (line 23)
router.get('/profile', UserController.getProfile)



📍 Controller Layer
📄 src/controllers/UserController.js (lines 45-78)
async getProfile(req, res) {
const userId = req.user.id;
const profile = await UserService.getProfile(userId);
// ... response handling
}



📍 Service Layer
📄 src/services/UserService.js (lines 123-156)
async getProfile(userId) {
const user = await User.findById(userId);
if (!user) {
throw new NotFoundError('User not found');
}
return this.sanitizeProfile(user);
}



📍 Model Layer
📄 src/models/User.js (lines 67-89)
static async findById(id) {
const query = 'SELECT * FROM users WHERE id = $1';
const result = await db.query(query, [id]);
return result.rows[0];
}

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📊 Statistics:
- Total layers: 4 (Route → Controller → Service → Model)
- Total files: 4
- Total functions: 4
- Database queries: 1
- Error handling points: 2

⚠️ Observations:
- Good separation of concerns
- Proper error handling in Service layer
- Missing input validation in Controller
- No caching mechanism (consider adding Redis cache)

💡 Suggestions:
1. Add request validation middleware
2. Implement profile caching (TTL: 5min)
3. Add database query logging
```

## 跳转到引用

### 查找所有使用位置

了解函数或变量在哪里被使用:

```
找出所有调用sendWelcomeEmail的地方
```

Claude Code会提供完整的引用分析:

```
📊 Usage Analysis: sendWelcomeEmail function

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Total References: 7 calls across 5 files

📄 src/controllers/UserController.js (3 calls)
Line 67: After user registration
await sendWelcomeEmail(user.email, user.name);
Context: New user signup flow

Line 145: After email verification
await sendWelcomeEmail(user.email, user.name, { verified: true });
Context: Email verification completion

Line 203: After email change
await sendWelcomeEmail(newUser.email, newUser.name, { emailChanged: true });
Context: Email address update

📄 src/controllers/AdminController.js (2 calls)
Line 89: Manual invitation
await sendWelcomeEmail(email, name, { invitedBy: admin.name });
Context: Admin invites user

Line 234: Bulk import
for (const user of importedUsers) {
await sendWelcomeEmail(user.email, user.name);
}
Context: Batch user import (⚠️ potential performance issue)

📄 src/services/onboardingService.js (1 call)
Line 45: During onboarding
await sendWelcomeEmail(user.email, user.name, { onboardingData });
Context: Post-registration onboarding flow

📄 src/tests/email.test.js (1 call)
Line 123: Test case
await sendWelcomeEmail('test@example.com', 'Test User');
Context: Unit test

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🔍 Pattern Analysis:
✓ Good: Consistent async/await usage
✓ Good: Error handling in all calling functions
⚠️ Issue: Bulk import may trigger rate limiting
⚠️ Issue: No retry mechanism for failed sends

💡 Recommendations:
1. Implement queue system for bulk operations
2. Add exponential backoff for retries
3. Monitor email delivery rates
4. Add unit tests for edge cases
```

### 依赖关系分析

理解模块之间的依赖关系:

```
分析OrderController的依赖关系
```

Claude Code会构建依赖图:

```
📊 Dependency Analysis: OrderController

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📥 Incoming Dependencies (Who depends on this?)
• src/routes/orderRoutes.js
→ Direct import: require('./controllers/OrderController')

• src/tests/order.test.js
→ Test import: require('../controllers/OrderController')

📤 Outgoing Dependencies (What does this depend on?)
Level 1 (Direct):
• src/services/OrderService.js
→ Used for: Order business logic
→ Functions: create, update, delete, getList

• src/services/PaymentService.js
→ Used for: Payment processing
→ Functions: processPayment, refund

• src/services/NotificationService.js
→ Used for: User notifications
→ Functions: sendOrderConfirmation

• src/middleware/validators.js
→ Used for: Input validation
→ Functions: validateOrderInput

• src/utils/logger.js
→ Used for: Logging
→ Functions: info, error, warn

• src/models/Order.js
→ Used for: Data model
→ Properties: schema definitions

Level 2 (Indirect):
• src/models/User.js (via OrderService)
• src/models/Product.js (via OrderService)
• src/services/EmailService.js (via NotificationService)
• src/database/db.js (via all models)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📈 Complexity Metrics:
• Direct dependencies: 6
• Total dependency depth: 3 levels
• Circular dependencies: 0 ✓
• Coupling score: Medium (acceptable)

⚠️ Potential Issues:
1. High coupling with services (6 services)
2. PaymentService and NotificationService could be abstracted
3. Consider using dependency injection

💡 Refactoring Suggestions:
1. Introduce service layer façade
2. Use dependency injection pattern
3. Consider event-driven architecture for notifications
```

## 全局搜索

### 跨文件类型搜索

Claude Code可以同时搜索多种文件类型:

```
在所有文件中搜索"API_KEY"
```

```
🔍 Global search for "API_KEY"...

Found in 12 files across multiple file types:

📄 Configuration Files (4 files)
.env.example
Line 3: API_KEY=your_api_key_here
Line 15: EXTERNAL_API_KEY=another_key

config/defaults.json
Line 8: "apiKey": "default_key"

webpack.config.js
Line 45: process.env.API_KEY

.env.development
Line 2: API_KEY=dev_12345

📄 Source Code (5 files)
src/services/api.js
Line 12: const API_KEY = process.env.API_KEY;
Line 67: headers: { 'X-API-Key': API_KEY }

src/utils/config.js
Line 23: apiKey: config.API_KEY || 'fallback'

src/controllers/externalApi.js
Line 34: const key = process.env.EXTERNAL_API_KEY;

📄 Documentation (3 files)
README.md
Line 78: Set `API_KEY` in your .env file
Line 134: Get your API key from: https://api.example.com

docs/deployment.md
Line 56: Export API_KEY before starting the server

docs/api-reference.md
Line 23: All requests require API_KEY in header

⚠️ Security Alert:
Found API keys that may be exposed:
• .env.development contains a hardcoded key (dev_12345)
• config/defaults.json contains default key

💡 Recommendations:
1. Add .env.development to .gitignore
2. Remove hardcoded keys from config files
3. Use environment-specific keys
4. Add API key validation
```

### 按目录范围搜索

限制搜索范围以提高精度:

```
在src/controllers目录中搜索所有使用try-catch的代码
```

```
🔍 Searching in src/controllers/ for "try-catch" patterns...

Found 34 try-catch blocks in 8 controller files:

📄 src/controllers/UserController.js (8 blocks)
Line 23-34: createUser method
Pattern: Standard error catching
Caught: Database errors
Response: 500 status with error message

Line 45-56: updateUser method
Pattern: Standard error catching
Caught: Validation errors
Response: 400 status with validation details

... (6 more)

📄 src/controllers/OrderController.js (6 blocks)
Line 12-28: createOrder method
Pattern: Standard error catching
Caught: Payment errors, validation errors
Response: Different status codes based on error type

... (4 more)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📊 Analysis Results:
Total try-catch blocks: 34
Average per file: 4.25 blocks
Error handling consistency: 75%

⚠️ Issues Found:
1. Inconsistent error response format (3 different patterns)
2. Missing error logging in 8 blocks
3. Generic error messages in 12 blocks
4. No error classification (user errors vs system errors)

💡 Refactoring Plan:
1. Create centralized error handler (save ~100 lines)
2. Implement error class hierarchy
3. Add error logging middleware
4. Standardize error response format

Would you like me to implement these improvements?
```

### 组合条件搜索

使用多个条件进行精确搜索:

```
找出所有:
1. 导入了useState但未使用的文件
2. 定义了async函数但没有await的文件
3. 有TODO注释超过30天的文件
```

Claude Code会执行复合分析:

```
🔍 Multi-condition analysis...

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Condition 1: useState imported but not used
Found 3 files:
src/components/UserProfile.jsx
Line 3: import { useState, useEffect } from 'react'
Analysis: useState imported but only useEffect is used
Action: Remove useState from import

src/components/Dashboard.jsx
Line 4: import { useState, useMemo } from 'react'
Analysis: useState imported but only useMemo is used
Action: Remove useState from import

src/hooks/useAuth.js
Line 2: import { useState, useEffect } from 'react'
Analysis: useState imported but was used in commented code
Action: Remove or uncomment usage

Condition 2: async functions without await
Found 2 files:
src/controllers/AuthController.js
Line 89: async loginWithoutAwait(req, res)
Analysis: Function marked async but has no await
Impact: Unnecessary promise wrapping
Fix: Remove async keyword

src/services/dataFetcher.js
Line 234: async fetchAllData()
Analysis: All promises are handled with .then() instead of await
Impact: Mixed async patterns
Fix: Convert to async/await or remove async

Condition 3: TODO comments older than 30 days
Found 7 TODOs:
src/services/paymentService.js (Line 45)
Created: 2024-10-15 (62 days ago)
Comment: // TODO: Implement PayPal integration
Priority: High (blocking feature)

src/utils/cache.js (Line 67)
Created: 2024-09-20 (87 days ago)
Comment: // TODO: Add Redis caching
Priority: Medium (performance improvement)

... (5 more)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🎯 Summary:
• Unused imports: 3 files (quick fixes)
• Async issues: 2 files (low priority)
• Old TODOs: 7 items (3 high priority)

🚀 Suggested Actions:
1. Fix unused imports (2 minutes)
2. Remove unnecessary async keywords (1 minute)
3. Create GitHub issues for old TODOs (5 minutes)
4. Implement high-priority TODOs (2-3 hours)

Would you like me to execute fixes for 1 and 2?
```

## 正则表达式搜索

### 基础正则搜索

对于复杂的模式匹配,Claude Code可以使用正则表达式:

```
用正则表达式找出所有的邮箱地址
```

Claude Code会自动构建合适的正则表达式:

```
🔍 Regex Search: Email addresses

Pattern used: [\w._%+-]+@[\w.-]+\.[A-Za-z]{2,}

Found 47 email addresses in 12 files:

📄 src/config/email.js (3 emails)
Line 12: noreply@example.com
Line 15: support@example.com
Line 18: admin@example.com

📄 tests/fixtures/users.json (15 emails)
Line 23: user1@example.com
Line 24: user2@example.com
... (13 more)

📄 docs/deployment.md (5 emails)
Line 78: Contact admin@example.com for access
Line 89: Send reports to reports@example.com
... (3 more)

⚠️ Security Check:
No real email addresses found (all are example.com domain)

💡 Suggestions:
1. Consolidate email configuration in one place
2. Use environment variables for production emails
3. Add email validation regex unit tests
```

### 复杂模式匹配

搜索更复杂的代码模式:

```
找出所有没有错误处理的数据库查询
```

Claude Code会构建复杂的正则模式:

```
🔍 Pattern Search: Database queries without error handling

Pattern analyzed:
• db.query calls without try-catch
• Model methods without error handling
• Direct SQL queries without .catch()

Found 15 queries without proper error handling:

📄 src/services/userService.js (5 queries)
Line 45: db.query('SELECT * FROM users WHERE id = ?', [id])
❌ No error handling
Impact: Database errors will crash the server
Fix: Wrap in try-catch or add .catch()

Line 67: await User.findByEmail(email)
❌ No error handling
Impact: Unhandled promise rejection
Fix: Add try-catch block

... (3 more)

📄 src/repositories/orderRepository.js (8 queries)
Line 23: connection.query(sql, params)
❌ No error handling
❌ No connection release on error
Impact: Connection leak + server crash
Fix: Wrap with error handling + cleanup

... (7 more)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🚨 Critical Issues:
• 15 queries can crash the server
• 8 queries may cause connection leaks
• 0% error handling coverage

💡 Refactoring Plan:
1. Create database wrapper with automatic error handling
2. Implement connection pool management
3. Add centralized error logging
4. Create helper functions for common queries

Example fix:
Before:
const result = await db.query('SELECT * FROM users');
return result.rows;

After:
try {
const result = await db.query('SELECT * FROM users');
return result.rows;
} catch (error) {
logger.error('Database query failed', { error });
throw new DatabaseError('Failed to fetch users');
}

Would you like me to implement these fixes?
```

### 代码气味检测

使用正则表达式检测常见的代码问题:

```
检测代码中的反模式:
1. console.log在生产代码中
2. 硬编码的密钥和密码
3. var关键字的使用
4. 嵌套超过4层的代码
```

```
🔍 Code Smell Detection

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Smell 1: console.log in production code
Found 23 occurrences:

📄 src/controllers/UserController.js (8 logs)
Line 34: console.log('User created:', user)
Severity: Medium
Impact: Performance issue, information leakage
Fix: Replace with logger.info()

Line 67: console.log(error)
Severity: High
Impact: Error details leaked to console
Fix: Replace with logger.error()

... (6 more)

📄 src/services/api.js (15 logs)
Line 123: console.log('API request:', data)
Severity: High
Impact: May leak sensitive data
Fix: Remove or use sanitized logging

Smell 2: Hardcoded secrets
Found 3 occurrences:

📄 src/config/db.js
Line 12: password: 'admin123'
Severity: CRITICAL
Impact: Security vulnerability
Action: Move to environment variable immediately

Line 15: apiKey: 'sk_live_abc123xyz'
Severity: CRITICAL
Impact: Exposed payment API key
Action: Rotate key and use environment variable

📄 src/services/external.js
Line 45: const secret = 'my_secret_key'
Severity: High
Impact: Hardcoded encryption key
Action: Generate unique key per environment

Smell 3: var keyword usage
Found 7 occurrences:

📄 src/utils/helpers.js (4 vars)
Line 23: var count = 0
Severity: Low
Impact: Outdated syntax
Fix: Replace with const or let

... (3 more)

Smell 4: Deep nesting (4+ levels)
Found 5 occurrences:

📄 src/controllers/OrderController.js
Line 89-123: 5 levels of nesting
Severity: Medium
Impact: Reduced readability
Fix: Extract nested logic into separate functions

📄 src/services/paymentService.js
Line 156-198: 6 levels of nesting
Severity: High
Impact: Cognitive complexity too high
Fix: Break down into smaller functions

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📊 Summary:
• Total issues: 38
• Critical: 3 (security)
• High: 18 (performance + security)
• Medium: 12 (readability)
• Low: 5 (style)

🎯 Priority Actions:
1. Rotate exposed API keys (DO IMMEDIATELY)
2. Move secrets to environment variables
3. Replace console.log with logger
4. Refactor deeply nested code

⏱️ Estimated time:
• Critical fixes: 30 minutes
• High priority fixes: 2 hours
• Medium + Low: 3 hours

Would you like me to start with the critical security fixes?
```

## 符号导航

### 类和接口导航

快速浏览类的结构和继承关系:

```
显示UserModel类的完整结构
```

```text
🏗️ Class Structure: UserModel

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📄 Location: src/models/User.js (lines 12-234)

📋 Class Hierarchy:
BaseModel
└── UserModel (extends BaseModel)

📦 Properties:
• id: string (UUID, primary key)
• email: string (unique, indexed)
• password: string (hashed)
• name: string
• role: enum ['user', 'admin', 'moderator']
• isActive: boolean (default: true)
• createdAt: Date
• updatedAt: Date
• lastLoginAt: Date (nullable)

🔧 Static Methods:
• findById(id): Promise[User]
Location: Line 45-56
Returns: User instance or null
Throws: NotFoundError

• findByEmail(email): Promise[User]
Location: Line 67-78
Returns: User instance or null
Indexes: email field

• create(data): Promise[User]
Location: Line 89-112
Validates: Email format, password strength
Hashes: Password before saving

• findAll(filters): Promise[User[]]
Location: Line 123-145
Supports: Pagination, filtering, sorting

🎯 Instance Methods:
• validate(): boolean
Location: Line 156-178
Checks: Email, password, required fields

• hashPassword(): Promise[void]
Location: Line 189-201
Algorithm: bcrypt (10 rounds)

• toJSON(): Object
Location: Line 212-234
Excludes: Password field
Includes: Safe user data only

🔗 Relationships:
• hasMany: Order (orders placed by user)
• hasMany: Review (reviews written by user)
• belongsToMany: Role (many-to-many via UserRoles)

📊 Statistics:
• Total lines: 223
• Methods: 8 (4 static, 4 instance)
• Properties: 8
• Relationships: 3
• Complexity: Medium

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

💡 Observations:
✓ Good: Follows MVC pattern
✓ Good: Password hashing implemented
✓ Good: Proper data hiding (toJSON excludes password)
⚠️ Issue: Missing soft delete functionality
⚠️ Issue: No email verification method
⚠️ Issue: Last login not updated on login

🎯 Recommended Enhancements:
1. Add soft delete (deletedAt timestamp)
2. Add email verification flow
3. Implement password reset method
4. Add profile picture handling
5. Cache frequently accessed users

Would you like me to implement any of these enhancements?
```

### 模块导出导航

理解模块的导出结构:

```
显示utils/helpers模块导出了哪些函数
```

```
📦 Module Exports: utils/helpers.js

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📄 File: src/utils/helpers.js (345 lines)

📤 Export List (17 exports):

Named Exports (15):
1. formatDate(date, format)
Line: 23-45
Usage: 23 files import this
Purpose: Date formatting with locale support

2. formatCurrency(amount, currency)
Line: 56-67
Usage: 12 files import this
Purpose: Currency formatting

3. validateEmail(email)
Line: 78-89
Usage: 18 files import this
Purpose: Email validation (regex)

4. validatePhone(phone)
Line: 90-101
Usage: 8 files import this
Purpose: Phone number validation

5. generateToken()
Line: 112-123
Usage: 5 files import this
Purpose: Random token generation

6. hashPassword(password)
Line: 134-145
Usage: 3 files import this
Purpose: Password hashing (bcrypt)

7. comparePassword(password, hash)
Line: 156-167
Usage: 3 files import this
Purpose: Password verification

8. sanitizeInput(input)
Line: 178-189
Usage: 15 files import this
Purpose: XSS protection

9. truncateText(text, length)
Line: 190-201
Usage: 9 files import this
Purpose: Text truncation with ellipsis

10. slugify(text)
Line: 212-223
Usage: 11 files import this
Purpose: URL-friendly string conversion

11. parseQuery(queryString)
Line: 234-256
Usage: 7 files import this
Purpose: Query string parsing

12. buildQuery(params)
Line: 267-289
Usage: 6 files import this
Purpose: Query object building

13. paginate(array, page, limit)
Line: 290-312
Usage: 14 files import this
Purpose: Array pagination

14. sortBy(array, key, order)
Line: 313-328
Usage: 10 files import this
Purpose: Array sorting

15. deepClone(obj)
Line: 329-338
Usage: 8 files import this
Purpose: Deep object cloning

Default Export (1):
HelperFunctions (object containing all functions)
Usage: 2 files use default import
Not recommended: Use named imports instead

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📊 Usage Statistics:
• Total exports: 17
• Most used: validateEmail (18 files)
• Least used: comparePassword (3 files)
• Average usage: 9.4 files per export

⚠️ Issues:
1. Default export is discouraged (prefer named)
2. hashPassword/comparePassword could be in auth module
3. Some functions could be from utility libraries

💡 Refactoring Suggestions:
1. Remove default export, use only named exports
2. Move auth functions to utils/auth.js
3. Consider using date-fns for date functions
4. Consider using lodash for clone/sort functions
5. Add TypeScript types

🎯 Migration Plan:
Phase 1: Add named imports to all files
Phase 2: Remove default export
Phase 3: Extract auth functions
Phase 4: Replace with library functions
```

### TypeScript类型导航

对于TypeScript项目,查看类型定义:

```
显示User interface的类型定义和所有实现
```

```
📘 Type Definition: User interface

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📄 Location: src/types/user.ts

📝 Interface Definition:
```typescript
interface User {
// Basic fields
id: string;
email: string;
name: string;

// Optional fields
phone?: string;
avatar?: string;
bio?: string;

// Timestamps
createdAt: Date;
updatedAt: Date;
lastLoginAt?: Date;

// Relationships
orders?: Order[];
reviews?: Review[];
role: UserRole;

// Methods
getFullName(): string;
isAdmin(): boolean;
}
```

🏷️ Type Extensions:
```typescript
// Extended types that inherit from User
interface AdminUser extends User {
permissions: Permission[];
department: string;
}

interface GuestUser extends User {
isGuest: true;
sessionToken: string;
}
```

📊 Implementation Statistics:
• Direct implementations: 3 classes
• Type usages: 47 files
• Interface extensions: 2 types
• Generic usages: 8 times

🔍 Implementations:
1. src/models/UserModel.ts (class)
Implements: User interface
Additional methods: save(), delete(), validate()

2. src/types/dto/UserDTO.ts (interface)
Extends: User
Adds: validation, serialization

3. src/services/userService.ts (type usage)
Uses: User type extensively
Functions: 15 functions return User

🎯 Type Safety Analysis:
✓ Good: No 'any' types used
✓ Good: Optional fields marked correctly
✓ Good: Method signatures defined
⚠️ Issue: Some fields could be readonly
⚠️ Issue: Missing index signature

💡 Improvements:
1. Add readonly modifier for id, createdAt
2. Add index signature for dynamic fields
3. Create partial type for updates
4. Add type guards for role checking

Example improvements:
Before:
interface User {
id: string;
createdAt: Date;
}

After:
interface User {
readonly id: string;
readonly createdAt: Date;
[key: string]: any; // For dynamic fields
}
```

## 跨文件搜索

### 多项目搜索

在monorepo或多项目结构中搜索:

```
在packages目录下的所有包中搜索"useEffect"
```

```
🔍 Cross-project search: "useEffect"

Searching in: /packages (monorepo)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Package: @myapp/web (frontend)
Path: packages/web/src
Found: 34 occurrences

📄 components/UserProfile.tsx (2 uses)
Line 12: useEffect(() => { /* load user */ }, [])
Line 45: useEffect(() => { /* update data */ }, [userId])

📄 components/Dashboard.tsx (3 uses)
Line 23: useEffect(() => { /* fetch stats */ }, [])
Line 67: useEffect(() => { /* refresh data */ }, [interval])
Line 89: useEffect(() => { /* cleanup */ }, [socket])

... (29 more)

Package: @myapp/admin (admin panel)
Path: packages/admin/src
Found: 28 occurrences

📄 pages/Users.tsx (4 uses)
Line 34: useEffect(() => { /* load users */ }, [])
... (3 more)

... (24 more)

Package: @myapp/shared (shared components)
Path: packages/shared/src
Found: 15 occurrences

📄 components/DataGrid.tsx (2 uses)
Line 56: useEffect(() => { /* setup grid */ }, [])
... (1 more)

... (13 more)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📊 Summary:
• Total packages searched: 3
• Total files: 77
• Total useEffect calls: 77
• Average per package: 25.7

⚠️ Common Issues Found:
1. Missing dependencies (12 cases)
Example: useEffect(() => {}, [userId])
Missing: fetchUser function dependency

2. Empty dependency arrays when shouldn't be (8 cases)
Example: useEffect(() => { console.log(userId) }, [])
Should be: [userId]

3. No cleanup functions (15 cases)
Example: useEffect(() => { subscribe() }, [])
Missing: Return unsubscribe function

💡 Refactoring Opportunities:
1. Extract effects to custom hooks
- useUserProfile (in 5 components)
- useDataFetch (in 12 components)
- useWebSocket (in 3 components)

2. Consolidate similar effects
- Save ~200 lines of code
- Improve consistency

3. Add effect dependency linting
- Enable exhaustive-deps rule
- Fix dependency arrays

🎯 Recommended Actions:
1. Run eslint to fix dependency arrays
2. Create custom hooks for common patterns
3. Add cleanup where needed
4. Document effect purposes

Would you like me to create the custom hooks?
```

### 配置文件搜索

搜索和对比配置文件:

```
对比所有环境配置文件中的API URL设置
```

```
🔍 Configuration Comparison: API URLs

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

File: .env.development
API_URL: http://localhost:3000/api
DB_URL: postgresql://localhost:5432/dev
REDIS_URL: redis://localhost:6379

File: .env.staging
API_URL: https://staging-api.example.com/api
DB_URL: postgresql://staging-db.example.com:5432/staging
REDIS_URL: redis://staging-redis.example.com:6379

File: .env.production
API_URL: https://api.example.com/api
DB_URL: postgresql://prod-db.example.com:5432/production
REDIS_URL: redis://prod-redis.example.com:6379

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📊 Consistency Check:
✓ All environments have API_URL defined
✓ All environments have DB_URL defined
✓ All environments have REDIS_URL defined

⚠️ Inconsistencies:
1. Development uses http, others use https
2. Port numbers differ (expected)
3. Domain naming pattern is consistent

❌ Missing Configuration:
1. .env.test is missing
2. No .env.example for reference
3. Some configs in code instead of env files

Files with hardcoded config:
• src/config/api.ts (line 12): API URL hardcoded
• src/services/db.js (line 23): DB connection string
• webpack.config.js (line 45): API proxy URL

💡 Recommendations:
1. Create .env.example with all required variables
2. Create .env.test for testing
3. Move hardcoded configs to environment variables
4. Add config validation on startup
5. Document all environment variables

🔧 Action Items:
1. Create .env.example
2. Move hardcoded configs
3. Add config validation
4. Create deployment guide

Would you like me to create the missing configuration files?
```

### 依赖关系搜索

查找模块间的依赖关系:

```
找出所有依赖lodash的文件,并分析每个文件使用了哪些lodash函数
```

```
🔍 Dependency Analysis: lodash usage

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📦 Package: lodash (version 4.17.21)
Bundle size: 70 KB (minified, not tree-shaken)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📄 src/utils/helpers.js
Import: import _ from 'lodash'
Functions used:
• _.map (3 times)
• _.filter (2 times)
• _.forEach (1 time)
• _.cloneDeep (4 times)
• _.isEmpty (5 times)
Impact: Imports entire lodash for 5 functions
Bundle size impact: ~70 KB

Recommendation:
import map from 'lodash/map'
import filter from 'lodash/filter'
... OR use native methods

📄 src/services/dataProcessor.js
Import: import { debounce, throttle } from 'lodash'
Functions used:
• _.debounce (2 times)
• _.throttle (1 time)
Impact: Tree-shakeable import (good)
Bundle size impact: ~2 KB

📄 src/components/DataTable.jsx
Import: import _ from 'lodash'
Functions used:
• _.sortBy (3 times)
• _.groupBy (2 times)
• _.uniq (1 time)
• _.get (8 times) - safe navigation
• _.set (4 times) - safe assignment
Impact: Imports entire lodash
Bundle size impact: ~70 KB

Recommendation:
Use native: array.sort(), array.filter()
Use optional chaining: obj?.prop instead of _.get(obj, 'prop')

📄 src/controllers/apiController.js
Import: import lodash from 'lodash'
Functions used:
• _.merge (2 times) - deep object merging
• _.pick (3 times) - object property selection
• _.omit (2 times) - object property exclusion
Impact: Imports entire lodash
Bundle size impact: ~70 KB

Recommendation:
Use spread operator for shallow merges
Use object destructuring for pick/omit

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📊 Summary:
• Files using lodash: 4
• Total functions used: 15 unique functions
• Total bundle impact: ~212 KB (3 full imports)
• Tree-shaken imports: 1 file

🎯 Optimization Plan:
Phase 1: Replace with native methods (save 140 KB)
• _.map → Array.prototype.map
• _.filter → Array.prototype.filter
• _.forEach → Array.prototype.forEach
• _.sortBy → Array.prototype.sort
• _.uniq → Set or Array.filter

Phase 2: Use modern JavaScript (save 70 KB)
• _.get → optional chaining (obj?.prop)
• _.set → optional chaining assignment (obj?.prop = val)
• _.isEmpty → Object.keys(obj).length === 0

Phase 3: Keep what's needed (keep 2 KB)
• _.debounce, _.throttle (hard to replace)
• _.cloneDeep (can use structuredClone)

💰 Potential Savings:
• Before: 212 KB
• After: 2 KB (debounce, throttle)
• Saved: 210 KB (99% reduction)

⏱️ Estimated refactoring time: 2 hours

Would you like me to perform this optimization?
```

## 实用技巧和最佳实践

### 技巧1: 智能搜索模式

使用更精确的搜索描述:

❌ 模糊搜索:
```
搜索关于用户的所有代码
```
结果: 返回上百个可能不相关的文件

✅ 精确搜索:
```
搜索用户注册流程中涉及邮箱验证的代码
```
结果: 返回5-10个高度相关的代码片段

### 技巧2: 组合搜索条件

使用多个条件缩小范围:

```
搜索满足以下所有条件的代码:
1. 在src/services目录
2. 包含async函数
3. 函数名包含"fetch"或"get"
4. 有error handling
5. 没有JSDoc注释
```

Claude Code会执行多维度分析:

```
🔍 Multi-criteria search in src/services/

Found 8 functions matching all criteria:

1. src/services/userService.js
Line 89: async fetchUserData(userId)
✓ Has error handling (try-catch)
✗ Missing JSDoc
Impact: Medium (used in 3 places)

2. src/services/apiService.js
Line 123: async getCustomerOrders(customerId)
✓ Has error handling (try-catch)
✗ Missing JSDoc
Impact: High (used in 7 places)

... (6 more)

📝 Suggested JSDoc for fetchUserData:
/**
* Fetches user data by user ID
* @async
* @param {string} userId - The user's unique identifier
* @returns {Promise<Object>} User data object
* @throws {NotFoundError} If user not found
* @throws {DatabaseError} If database query fails
*/
```

### 技巧3: 代码模式识别

让Claude Code识别特定的代码模式:

```
识别项目中的所有单例模式实现
```

```
🔍 Pattern Recognition: Singleton

Found 4 singleton implementations:

Pattern 1: Module Export Pattern (2 instances)
📄 src/services/database.js
Line 23-45
```javascript
class Database {
constructor() {
if (Database.instance) {
return Database.instance;
}
this.connection = null;
Database.instance = this;
}
}
module.exports = new Database();
```
✓ Thread-safe in Node.js
✓ Easy to use
⚠️ Cannot be reset for testing

Pattern 2: Closure Pattern (1 instance)
📄 src/services/cache.js
Line 12-34
```javascript
const Cache = (function() {
let instance;
function createInstance() {
return new CacheService();
}
return {
getInstance: function() {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
```
✓ Private instance
✓ Lazy initialization
⚠️ More complex syntax

Pattern 3: Class Static Property (1 instance)
📄 src/services/logger.js
Line 56-78
```javascript
class Logger {
static instance = null;

static getInstance() {
if (!Logger.instance) {
Logger.instance = new Logger();
}
return Logger.instance;
}
}
```
✓ Clean syntax
✓ Standard pattern
✓ Testable (can reset instance)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

💡 Recommendation:
Standardize on Pattern 3 (Class Static Property)
• Most readable
• Easy to test
• Common pattern
• TypeScript-friendly

Would you like me to refactor all singletons to use Pattern 3?
```

### 技巧4: 性能分析

搜索性能相关的代码:

```
找出所有可能导致性能问题的代码:
1. 循环中的数据库查询
2. 大数组操作没有分页
3. 未优化的正则表达式
4. 同步文件操作
```

```
🔍 Performance Issues Detection

Found 23 potential performance issues:

🚨 Critical Issues (5):

1. src/services/userService.js (Line 89-95)
Issue: N+1 query problem
```javascript
for (const user of users) {
const orders = await db.query(
'SELECT * FROM orders WHERE user_id = ?',
[user.id]
); // Query inside loop!
}
```
Impact: 1000 users = 1001 queries
Fix: Use JOIN or batch queries
Estimated improvement: 100x faster

2. src/controllers/dataController.js (Line 145-167)
Issue: Loading entire dataset into memory
```javascript
const allData = await fs.readFile('large-file.json');
const data = JSON.parse(allData); // 500MB file!
```
Impact: High memory usage, slow processing
Fix: Use streaming
Estimated improvement: 80% memory reduction

3. src/utils/parser.js (Line 234)
Issue: Catastrophic backtracking regex
```javascript
const regex = /^(a+)+$/; // Dangerous pattern
```
Impact: Can hang on certain inputs
Fix: Rewrite regex without nested quantifiers
Estimated improvement: Prevent DoS

4. src/services/exportService.js (Line 78)
Issue: Synchronous file operation in async function
```javascript
async function exportData() {
const data = fs.readFileSync('file.json'); // Blocks!
}
```
Impact: Blocks event loop
Fix: Use fs.promises.readFile
Estimated improvement: Non-blocking

5. src/components/DataTable.jsx (Line 89-123)
Issue: Rendering 10,000 rows without virtualization
```javascript
{allRows.map(row => <Row data={row} />)} // Too slow!
```
Impact: Slow rendering, frozen UI
Fix: Use react-window or react-virtualized
Estimated improvement: 100x faster render

⚠️ Medium Issues (12):
- Missing database indexes (8 cases)
- Unnecessary re-renders (4 cases)
- Large bundle size (no code splitting)

💡 Low Priority (6):
- Minor memory leaks
- Inefficient array operations
- Missing caching

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🎯 Quick Wins (Fix under 1 hour each):
1. Fix N+1 queries → Batch queries (30 min)
2. Replace sync file ops with async (15 min)
3. Add virtualization to DataTable (45 min)
4. Fix dangerous regex (10 min)

📈 Expected Overall Improvement:
• Query performance: 100x faster
• UI responsiveness: 10x better
• Memory usage: 60% reduction
• Bundle size: 40% smaller (after code splitting)

⏱️ Total estimated time: 3 hours

Would you like me to start with the critical issues?
```

### 技巧5: 安全漏洞检测

搜索潜在的安全问题:

```
检测安全漏洞:
1. SQL注入风险
2. XSS漏洞
3. 敏感数据泄露
4. 不安全的随机数生成
```

```
🔍 Security Vulnerability Scan

Found 18 security vulnerabilities:

🔴 Critical (6):

1. src/controllers/userController.js (Line 89)
Vulnerability: SQL Injection
```javascript
const query = `SELECT * FROM users WHERE id = ${userId}`;
// Direct string interpolation!
```
Severity: CRITICAL
Impact: Data breach, data loss
Fix: Use parameterized queries
```javascript
const query = 'SELECT * FROM users WHERE id = ?';
await db.query(query, [userId]);
```

2. src/components/Comment.jsx (Line 56)
Vulnerability: XSS (Cross-Site Scripting)
```javascript
<div dangerouslySetInnerHTML={{ __html: userComment }} />
// Unsanitized user input!
```
Severity: CRITICAL
Impact: Session hijacking, data theft
Fix: Sanitize input or use DOMPurify
```javascript
import DOMPurify from 'dompurify';
<div dangerouslySetInnerHTML={{
__html: DOMPurify.sanitize(userComment)
}} />
```

3. src/services/auth.js (Line 123)
Vulnerability: Timing attack on password comparison
```javascript
if (user.password === inputPassword) // Unsafe comparison
```
Severity: HIGH
Impact: Password bypass possible
Fix: Use bcrypt.compare()
```javascript
await bcrypt.compare(inputPassword, user.password);
```

4. src/config.js (Line 12)
Vulnerability: Hardcoded secret key
```javascript
const JWT_SECRET = 'my-secret-key-123';
```
Severity: CRITICAL
Impact: Token forgery, authentication bypass
Fix: Use environment variable with strong key

5. src/utils/crypto.js (Line 45)
Vulnerability: Weak random number generation
```javascript
const token = Math.random().toString(36); // Predictable!
```
Severity: HIGH
Impact: Session hijacking
Fix: Use crypto.randomBytes()
```javascript
const token = require('crypto').randomBytes(32).toString('hex');
```

6. src/api/payment.js (Line 234)
Vulnerability: Logging sensitive data
```javascript
logger.info('Payment:', { cardNumber, cvv }); // Leaking CVV!
```
Severity: CRITICAL
Impact: PCI-DSS compliance violation, fraud
Fix: Never log sensitive data

🟡 High Priority (5):
- Missing CSRF tokens
- Insecure cookie settings (no httpOnly, sameSite)
- CORS misconfiguration
- Missing rate limiting
- Weak password requirements

🟢 Medium Priority (7):
- Missing security headers
- Outdated dependencies
- Error messages leak info
- Missing input validation
- No HTTPS enforcement

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🚨 Immediate Action Required:
1. Fix SQL injection (30 minutes)
2. Fix XSS vulnerabilities (1 hour)
3. Remove hardcoded secrets (15 minutes)
4. Fix timing attack (15 minutes)
5. Stop logging sensitive data (10 minutes)

Total time: ~2 hours

📋 Security Checklist:
□ Parameterized all database queries
□ Sanitized all user inputs
□ Using environment variables for secrets
□ Implementing proper password hashing
□ Using secure random generation
□ Not logging sensitive data
□ Implementing CSRF protection
□ Securing cookies with httpOnly, sameSite, secure
□ Configuring CORS correctly
□ Adding rate limiting

Would you like me to fix these critical security issues?
```

## 常见问题解答

### Q: 如何搜索注释中的TODO标记?

**A:** 有几种方式:

```
# 方式1: 简单搜索
搜索所有的TODO注释

# 方式2: 按优先级搜索
找到所有标记为urgent或critical的TODO

# 方式3: 按时间搜索
找出所有30天前的TODO注释

# 方式4: 按作者搜索
搜索所有我写的TODO注释(假设注释中有作者)
```

Claude Code会找到所有TODO并提供分析:

```
📝 TODO Analysis

Found 47 TODOs in the codebase:

By Priority:
• Critical: 5 (blocking release)
• High: 12 (important features)
• Medium: 18 (improvements)
• Low: 12 (nice to have)

By Age:
• > 90 days: 8 (stale)
• 30-90 days: 15 (needs attention)
• < 30 days: 24 (recent)

By Category:
• Features: 20
• Bug fixes: 8
• Refactoring: 12
• Documentation: 7

🎯 Recommended Actions:
1. Address 5 critical TODOs (blocking release)
2. Convert stale TODOs to GitHub issues
3. Schedule high-priority TODOs for next sprint
```

### Q: 如何查找未使用的代码?

**A:** 让Claude Code分析依赖关系:

```
找出所有未被使用的:
1. 函数
2. 组件
3. 导入的模块
4. 类型定义
```

Claude Code会进行深度分析:

```
🔍 Unused Code Detection

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Unused Functions (12):
src/utils/helpers.js
• formatPhoneNumber() - defined but never called
• parseUserAgent() - defined but never called
• ... (10 more)

Unused Components (5):
src/components/
• OldDashboard.jsx - imported in no files
• BetaFeature.jsx - imported in no files
• ... (3 more)

Unused Imports (34):
src/pages/Home.jsx
Line 3: import { unusedFunction } from './utils'
Line 5: import { useState, useEffect } from 'react'
// Only useEffect is used

... (32 more)

Unused Type Definitions (7):
src/types/
• LegacyUser - not referenced anywhere
• OldApiResponse - not referenced anywhere
• ... (5 more)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

💰 Cleanup Potential:
• Lines of code: ~2,400
• Files: 12 completely unused
• Import cleanup: 34 files
• Bundle size reduction: ~15%

⚠️ Caution:
Before deleting, verify:
1. Not used dynamically (e.g., string references)
2. Not exported for external use
3. Not used in tests (separate test imports)
4. Not part of public API

Would you like me to:
1. Create a cleanup plan
2. Delete automatically (with git backup)
3. Show more details first
```

### Q: 如何理解复杂的代码逻辑?

**A:** 让Claude Code进行代码分析:

```
解释一下src/services/paymentService.js中的processPayment方法是如何工作的
```

Claude Code会提供详细的解释:

```
📖 Code Explanation: processPayment method

📄 Location: src/services/paymentService.js (lines 123-234)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🎯 Purpose:
Processes payment transactions through multiple payment providers
with automatic fallback and error handling.

📋 Algorithm Overview:

Step 1: Validation (lines 125-145)
• Validates payment amount (must be > 0)
• Checks card number format (Luhn algorithm)
• Verifies expiry date is in future
• Ensures CVV is 3-4 digits
If validation fails → throws ValidationError

Step 2: Load User Payment Methods (lines 147-167)
• Fetches stored payment methods from database
• Decrypts card details (using encryption key)
• Checks if card is still valid
If no valid cards → throws NoPaymentMethodError

Step 3: Primary Payment Attempt (lines 169-189)
• Attempts payment with primary provider (Stripe)
• Sends amount + card details
• Waits for response (max 30 seconds)
If successful → saves transaction, returns result
If failed with network error → proceeds to Step 4
If failed with payment error → throws PaymentError

Step 4: Fallback Payment Attempt (lines 191-211)
• Attempts payment with backup provider (PayPal)
• Same data as primary attempt
If successful → saves transaction, returns result
If failed → throws PaymentFailedError

Step 5: Record Transaction (lines 213-234)
• Saves transaction record to database
• Includes: provider, amount, status, timestamp
• Updates user's payment history
• Sends confirmation email

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🔄 Flow Diagram:
User Input

[Validation] ← fail → ValidationError
↓ pass
[Load Methods] ← fail → NoPaymentMethodError
↓ success
[Primary Payment] ← network error → [Fallback Payment]
↓ success ↓ success
[Record Transaction] ←─────────────── [Record Transaction]

Return Success

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

💡 Key Design Patterns:
1. **Strategy Pattern**: Multiple payment providers
2. **Circuit Breaker**: Automatic fallback on failure
3. **Transaction Logging**: Complete audit trail
4. **Error Handling**: Specific error types
5. **Security**: Encrypted card details

⚠️ Potential Issues:
1. Synchronous card loading (could be slow)
2. No retry mechanism for transient failures
3. Fallback always triggered (even for invalid cards)
4. Transaction logging happens after payment (race condition)

🎯 Improvement Suggestions:
1. Load payment methods asynchronously
2. Add retry logic with exponential backoff
3. Validate card before attempting payment
4. Log transaction before payment (intent)
5. Add idempotency key to prevent double charges

Would you like me to implement any of these improvements?
```

### Q: 如何查找代码的演进历史?

**A:** 结合Git历史进行分析:

```
显示UserController.js的演进历史,包括:
1. 什么时候创建的
2. 主要的修改节点
3. 代码行数变化
4. 贡献者
```

Claude Code会分析Git历史:

```
📜 Code Evolution: UserController.js

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📅 Creation:
Date: 2024-03-15 (9 months ago)
Author: Zhang San
Initial commit: a1b2c3d
Initial lines: 45

📊 Size Evolution:
• 2024-03-15: 45 lines (initial)
• 2024-04-20: 89 lines (+44, validation added)
• 2024-06-15: 134 lines (+45, error handling)
• 2024-08-10: 156 lines (+22, logging)
• 2024-10-05: 167 lines (+11, tests)
• Current: 167 lines

Growth: 122 lines in 9 months (~13 lines/month)

🔄 Major Commits (5):

1. 2024-10-05 (2 weeks ago) by Li Si
Commit: f3e4d5c
Message: "Add unit tests for UserController"
Changes: +11 lines, -0 lines
Files modified: 2 (controller + tests)
Impact: Test coverage increased from 45% to 78%

2. 2024-08-10 (2 months ago) by Wang Wu
Commit: b2c3d4e
Message: "Add comprehensive logging to UserController"
Changes: +22 lines, -0 lines
Added: Logger integration, 8 log points
Impact: Better debugging capability

3. 2024-06-15 (4 months ago) by Zhang San
Commit: a1b2c3d
Message: "Implement error handling middleware"
Changes: +45 lines, -12 lines
Added: Try-catch blocks, custom errors
Removed: Inline error responses
Impact: Consistent error responses

4. 2024-04-20 (6 months ago) by Li Si
Commit: 9f8e7d6
Message: "Add input validation to all endpoints"
Changes: +44 lines, -3 lines
Added: express-validator middleware
Impact: Better security, data integrity

5. 2024-03-15 (9 months ago) by Zhang San
Commit: 8d7f6e5
Message: "Initial implementation of UserController"
Changes: +45 lines (initial commit)
Features: CRUD operations for users

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

👥 Contributors:
• Zhang San: 2 commits (40%)
• Li Si: 2 commits (40%)
• Wang Wu: 1 commit (20%)

📈 Quality Metrics:
• Test coverage: 78% (started at 0%)
• Code complexity: Medium (cyclomatic complexity: 8)
• Technical debt: Low (no major issues)
• Documentation: Good (JSDoc on all methods)

🔍 Code Quality Evolution:
• Initial: Basic CRUD, no error handling
• +2 months: Added validation
• +4 months: Added error handling
• +6 months: Added logging
• +8 months: Added tests
Current: Production-ready, well-tested

💡 Observations:
✓ Consistent improvement over time
✓ Multiple contributors (good knowledge sharing)
✓ Focus on quality (tests, logging, validation)
⚠️ Slower growth recently (maintainance mode)

🎯 Recommendations:
1. Consider adding integration tests
2. Document API endpoints (Swagger)
3. Add performance monitoring
4. Consider code review checklist

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Would you like me to:
1. Show detailed diff for any commit
2. Compare two versions
3. Analyze contributor patterns
4. Generate changelog
```

## 总结

代码搜索与导航是Claude Code的核心优势之一。相比传统IDE的快捷键和复杂搜索面板,Claude Code通过自然语言就能完成所有搜索和导航任务。

### 核心优势

**1. 智能理解**
- 理解代码语义,不只是文本匹配
- 识别代码模式和设计模式
- 分析依赖关系和影响范围

**2. 全面分析**
- 跨文件、跨项目搜索
- 组合多个搜索条件
- 提供上下文和建议

**3. 自然交互**
- 无需记忆快捷键
- 用自然语言描述需求
- 对话式探索代码

**4. 深度洞察**
- 性能问题检测
- 安全漏洞扫描
- 代码质量分析
- 演进历史追踪

### 最佳实践

**搜索技巧:**
1. ✅ 用精确描述而不是模糊关键词
2. ✅ 组合多个条件缩小搜索范围
3. ✅ 让Claude Code分析代码而不只是查找文本
4. ✅ 利用代码理解功能学习复杂逻辑

**导航技巧:**
1. ✅ 追踪完整调用链理解系统架构
2. ✅ 分析依赖关系评估修改影响
3. ✅ 查看代码演进历史理解设计决策
4. ✅ 使用符号导航快速定位定义和引用

**分析技巧:**
1. ✅ 定期搜索未使用的代码并清理
2. ✅ 检测安全漏洞和性能问题
3. ✅ 分析代码模式并统一重构
4. ✅ 理解代码质量指标

### 实用场景

**日常开发:**
- 快速定位函数定义和引用
- 理解复杂的代码逻辑
- 查找相似代码进行复用

**代码审查:**
- 分析代码影响范围
- 检测潜在问题
- 理解修改上下文

**重构优化:**
- 找到所有需要修改的地方
- 分析代码结构
- 识别重构机会

**学习理解:**
- 理解系统架构
- 学习设计模式
- 追踪代码演进

掌握这些搜索和导航技巧,能更高效地理解和操作代码库,把精力集中在解决问题而不是寻找代码上。

## 下一步

- 学习 [代码编辑与重构](/claude-code/02-核心功能/code-editing) - 深入了解代码级别的编辑操作
- 探索 [Agent模式](/claude-code/02-核心功能/agent-mode) - 让Claude Code自主完成复杂任务
- 掌握 [Think模式](/claude-code/03-高级特性/think-mode) - 使用思维链提升复杂任务处理能力