@claude-powers/slash-commands
Version:
π Claude Powers - Essential slash commands for Claude Code
802 lines (668 loc) β’ 24.7 kB
Markdown
# Explain Code Command
Generates intelligent and didactic code explanations using advanced AI to accelerate understanding, onboarding, and reviews.
## Description
The `/explain-code` command is your personal code tutor that transforms complex code into clear explanations:
- **Contextual explanations** adapted to the developer's level
- **Data flow analysis** and program control
- **Detection of patterns** and architectures used
- **Business logic** extracted and clearly explained
- **Automatic diagrams** to visualize the logic
- **Interactive examples** to facilitate understanding
- **Onboarding assistance** for new developers
- **Code review insights** to improve quality
- **Automatic documentation generation**
## Usage
```
/explain-code [file] [--level] [--format] [--focus] [--diagram]
```
### Parameters
- `file`: Specific file to explain
- `--level`: Audience level (beginner, intermediate, expert, mixed-team)
- `--format`: Output format (detailed, summary, interactive, documentation)
- `--focus`: Specific aspect (logic, architecture, performance, security, patterns)
- `--diagram`: Generate diagrams (flowchart, sequence, architecture, data-flow)
- `--context`: Project context (startup, enterprise, legacy, educational)
- `--language`: Explanation language (spanish, english, french, etc.)
- `--examples`: Include practical examples
### Examples
```
/explain-code src/utils/dataProcessor.js
/explain-code --level=beginner --format=interactive --diagram=flowchart
/explain-code components/UserAuth.tsx --focus=security --level=expert
/explain-code api/payment.js --format=documentation --context=enterprise
/explain-code --focus=architecture --diagram=sequence --level=mixed-team
/explain-code legacy/billing.js --level=intermediate --examples=true
```
## Types of Explanations
### π Detailed Explanation for Beginners
```javascript
// Original code
const processUserData = async (users) => {
return await Promise.all(
users
.filter(user => user.isActive && user.lastLogin > Date.now() - 30 * 24 * 60 * 60 * 1000)
.map(async user => {
const profile = await fetchUserProfile(user.id);
const preferences = await getUserPreferences(user.id);
return {
...user,
profile: profile?.data || {},
preferences: preferences?.settings || {},
score: calculateUserScore(user, profile?.data)
};
})
);
};
// β¨ AUTOMATICALLY GENERATED EXPLANATION:
π STEP-BY-STEP EXPLANATION:
==========================
π― FUNCTION PURPOSE:
This function processes a list of users to create an enriched summary
for each active user who has recently logged in.
π WHAT THE FUNCTION DOES:
1οΈβ£ FILTERING ACTIVE USERS:
β’ Takes a list of users as input
β’ Filters only users who are "active" (user.isActive = true)
β’ Additionally filters users who have logged in within the last 30 days
π‘ 30-DAY CALCULATION:
30 * 24 * 60 * 60 * 1000 = 30 days in milliseconds
Date.now() - 30 days = timestamp from exactly 30 days ago
2οΈβ£ DATA ENRICHMENT:
For each user that passes the filter:
β’ Retrieves their complete profile from the server (fetchUserProfile)
β’ Retrieves their user preferences (getUserPreferences)
β’ Both operations are asynchronous (await)
3οΈβ£ CREATING THE FINAL OBJECT:
Combines the original user information with:
β’ Profile data (or an empty object {} if no data)
β’ User preferences (or an empty object {} if no settings)
β’ A calculated score based on the user and their profile
4οΈβ£ PARALLEL PROCESSING:
β’ Promise.all() executes all async operations in parallel
β’ This is VERY important for performance: instead of waiting for each
user one by one, it processes all simultaneously
π§ EXPLAINED TECHNICAL CONCEPTS:
π¦ SPREAD OPERATOR (...user):
Copies all properties from the 'user' object to the new object.
It's like saying "include everything the original user already had"
π‘οΈ OPTIONAL CHAINING (?.):
profile?.data means "if profile exists, give me profile.data,
otherwise, return undefined"
π NULLISH COALESCING (||):
profile?.data || {} means "use profile.data if it exists,
otherwise use an empty object {}"
β‘ ASYNC/AWAIT:
Allows writing asynchronous code that reads like synchronous code.
Each 'await' pauses the function until the promise resolves.
π PROMISE.ALL():
Executes multiple promises in parallel and waits for all of them to complete.
If you have 100 users, the 200 API calls (profile + preferences)
are executed at the same time instead of sequentially.
π‘ TYPICAL USE CASES:
β’ Dashboard showing active users with complete information
β’ Recommendation system based on user scores
β’ User activity reports for administrators
β’ Gamification systems requiring enriched data
β οΈ IMPORTANT CONSIDERATIONS:
β’ This function can make many simultaneous API calls
β’ Consider rate limiting if the user list is very large
β’ Handle errors: what happens if fetchUserProfile fails?
β’ The 30-day calculation assumes timestamps in milliseconds
π― SUGGESTED IMPROVEMENTS:
1. Add error handling with try/catch
2. Implement batch fetching to reduce API calls
3. Add logging for debugging
4. Consider caching for profiles that do not change frequently
```
### ποΈ Architectural Explanation for Teams
```javascript
// Original code: Authentication system
class AuthenticationService {
constructor(tokenService, userRepository, auditLogger) {
this.tokenService = tokenService;
this.userRepository = userRepository;
this.auditLogger = auditLogger;
}
async authenticate(credentials) {
const user = await this.userRepository.findByEmail(credentials.email);
if (!user || !await this.validatePassword(credentials.password, user.hashedPassword)) {
await this.auditLogger.logFailedAttempt(credentials.email);
throw new AuthenticationError('Invalid credentials');
}
const token = await this.tokenService.generateToken(user);
await this.auditLogger.logSuccessfulLogin(user);
return { user, token };
}
}
// β¨ GENERATED ARCHITECTURAL EXPLANATION:
ποΈ ARCHITECTURAL ANALYSIS:
==========================
π IDENTIFIED DESIGN PATTERNS:
β’ DEPENDENCY INJECTION: The class receives its dependencies in the constructor
β’ SERVICE LAYER: Encapsulates authentication business logic
β’ REPOSITORY PATTERN: Abstracts user data access
β’ SINGLE RESPONSIBILITY: Only handles authentication
π DEPENDENCY DIAGRAM:
```
AuthenticationService
βββ TokenService (Token generation/validation)
βββ UserRepository (User data access)
βββ AuditLogger (Security logging)
```
π― ADVANTAGES OF THIS ARCHITECTURE:
1οΈβ£ TESTABILITY:
β’ Easy to unit test with mocks of dependencies
β’ Each service can be tested independently
2οΈβ£ FLEXIBILITY:
β’ Token implementation can be changed (JWT β OAuth)
β’ Database can be changed without affecting logic
β’ Logging system can be changed independently
3οΈβ£ SEPARATION OF CONCERNS:
β’ AuthService: Only authentication logic
β’ TokenService: Only token handling
β’ UserRepository: Only data access
β’ AuditLogger: Only security logging
π SECURITY FLOW:
1. Credential validation
2. Logging of failed attempts (security audit)
3. Secure token generation
4. Logging of successful logins (compliance)
5. Return authorized information
π SCALABILITY:
β’ Each service can scale independently
β’ Cache can be implemented in UserRepository
β’ AuditLogger can be made asynchronous
β’ TokenService can use clusters for performance
π APPLIED ENTERPRISE PATTERNS:
β’ β
Dependency Injection
β’ β
Repository Pattern
β’ β
Service Layer
β’ β
Error Handling Strategy
β’ β
Audit Trail Pattern
β’ β
Secure Token Generation
π― USE IN HEXAGONAL ARCHITECTURE:
```
βββββββββββββββββββββββ
β Authentication β β Application Service
β Service β
βββββββββββββββββββββββ
β
βββββββΌββββββ
β β β
βΌ βΌ βΌ
ββββββββ ββββββββ ββββββββ
βToken β βUser β βAudit β β Domain Services
βSvc β βRepo β βLog β
ββββββββ ββββββββ ββββββββ
```
π‘ TEAM RECOMMENDATIONS:
β’ Ideal for teams that value clean architecture
β’ Perfect for enterprise applications that need audit trails
β’ Facilitates onboarding of new developers
β’ Allows parallel development of different services
```
### π¨ Visual Explanation with Diagrams
```javascript
// Code: Payment processing system
const processPayment = async (order, paymentMethod) => {
const validation = await validateOrder(order);
if (!validation.isValid) throw new Error(validation.error);
const payment = await chargePayment(paymentMethod, order.total);
if (payment.status === 'failed') {
await logFailedPayment(order, payment);
throw new PaymentError(payment.errorMessage);
}
const updatedOrder = await updateOrderStatus(order.id, 'paid');
await sendConfirmationEmail(order.customer.email, updatedOrder);
await logSuccessfulPayment(order, payment);
return { order: updatedOrder, payment };
};
// β¨ AUTOMATICALLY GENERATED DIAGRAM:
π¨ GENERATED FLOWCHART DIAGRAM:
=============================
```mermaid
flowchart TD
A[Start: processPayment] --> B[validateOrder]
B --> C{validation.isValid?}
C -->|No| D[Throw Error]
C -->|Yes| E[chargePayment]
E --> F{payment.status === 'failed'?}
F -->|Yes| G[logFailedPayment]
G --> H[Throw PaymentError]
F -->|No| I[updateOrderStatus to 'paid']
I --> J[sendConfirmationEmail]
J --> K[logSuccessfulPayment]
K --> L[Return result]
style A fill:#e1f5fe
style D fill:#ffebee
style H fill:#ffebee
style L fill:#e8f5e8
```
π SEQUENCE DIAGRAM:
========================
```mermaid
sequenceDiagram
participant Client
participant PaymentService
participant OrderValidator
participant PaymentGateway
participant Database
participant EmailService
participant Logger
Client->>PaymentService: processPayment(order, paymentMethod)
PaymentService->>OrderValidator: validateOrder(order)
OrderValidator-->>PaymentService: validation result
alt validation failed
PaymentService-->>Client: throw Error
else validation passed
PaymentService->>PaymentGateway: chargePayment(method, total)
PaymentGateway-->>PaymentService: payment result
alt payment failed
PaymentService->>Logger: logFailedPayment()
PaymentService-->>Client: throw PaymentError
else payment success
PaymentService->>Database: updateOrderStatus('paid')
PaymentService->>EmailService: sendConfirmationEmail()
PaymentService->>Logger: logSuccessfulPayment()
PaymentService-->>Client: return {order, payment}
end
end
```
π IDENTIFIED CRITICAL POINTS:
================================
π¨ ERROR HANDLING:
β’ 2 main failure points: validation and payment
β’ Differentiated logging for troubleshooting
β’ Specific error types for different failures
β‘ PERFORMANCE CONSIDERATIONS:
β’ updateOrderStatus and sendConfirmationEmail could be parallel
β’ logSuccessfulPayment could be asynchronous (fire-and-forget)
π SECURITY ASPECTS:
β’ Mandatory validation before processing payment
β’ Complete logging for audit trail
β’ Error messages do not expose sensitive information
π° BUSINESS LOGIC:
β’ Transactional: order status only updates after successful payment
β’ Email confirmation is part of the critical flow
β’ Logging for compliance and analytics
```
### π Interactive Educational Explanation
```javascript
// Code: Binary search algorithm
const binarySearch = (arr, target) => {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
};
// β¨ INTERACTIVE EDUCATIONAL EXPLANATION:
π INTERACTIVE TUTORIAL: BINARY SEARCH
======================================
π WHAT IS BINARY SEARCH?
It is an ultra-efficient search algorithm that works by
"dividing and conquering" a sorted array.
π― REAL-WORLD ANALOGY:
Imagine searching for a word in a dictionary:
1. Open to the middle
2. If the word is before, search the left half
3. If it's after, search the right half
4. Repeat until found
β‘ WHY IS IT SO FAST?
β’ 1,000-element array: maximum 10 comparisons
β’ 1,000,000-element array: maximum 20 comparisons
β’ Complexity: O(log n) vs O(n) for linear search
π STEP-BY-STEP WITH EXAMPLE:
===========================
Let's search for the number 7 in [1, 3, 5, 7, 9, 11, 13, 15]
π ITERATION 1:
left=0, right=7, mid=3
arr[3] = 7 β FOUND!
π RESULT: index 3
π MORE COMPLEX EXAMPLE:
Let's search for the number 11 in [1, 3, 5, 7, 9, 11, 13, 15]
π ITERATION 1:
left=0, right=7, mid=3
arr[3] = 7 < 11 β search right
left = 4
π ITERATION 2:
left=4, right=7, mid=5
arr[5] = 11 β FOUND!
π RESULT: index 5
π§ EXPLAINED KEY CONCEPTS:
π― ALGORITHM INVARIANT:
"If the target exists in the array, it will always be between left and right"
π MIDPOINT CALCULATION:
Math.floor((left + right) / 2) ensures mid is an integer
Why Math.floor? To avoid decimal indices
βοΈ LOGICAL DECISION:
β’ arr[mid] === target β Found β
β’ arr[mid] < target β target is to the right β
β’ arr[mid] > target β target is to the left β
π STOPPING CONDITION:
left > right means we have exhausted all possibilities
Target does not exist in the array β return -1
β οΈ CRITICAL PREREQUISITE:
THE ARRAY MUST BE SORTED!
If not sorted, the algorithm will NOT work correctly.
π REAL USE CASES:
β’ Searching in indexed databases
β’ Autocomplete in web search
β’ Recommendation systems
β’ Machine learning algorithms
β’ Any search in sorted data
πͺ INTERACTIVE EXPERIMENT:
Try modifying the target and see how the number of iterations changes:
β’ Target 1: 1 iteration (worst case left)
β’ Target 15: 2 iterations (worst case right)
β’ Target 8: 4 iterations (does not exist)
π‘ ADVANCED OPTIMIZATIONS:
β’ Interpolation search for uniformly distributed data
β’ Exponential search for very large arrays
β’ Ternary search for finding max/min
```
## Configuration
`.claude/explain-code-config.json`:
```json
{
"audience": {
"beginner": {
"includeBasicConcepts": true,
"useAnalogies": true,
"stepByStepBreakdown": true,
"avoidJargon": true,
"includeExamples": true
},
"intermediate": {
"assumeBasicKnowledge": true,
"focusOnPatterns": true,
"includePerformanceNotes": true,
"showAlternatives": true
},
"expert": {
"technicalDepth": "high",
"focusOnArchitecture": true,
"includeOptimizations": true,
"discussTradeoffs": true,
"showAdvancedPatterns": true
},
"mixedTeam": {
"multiLevelExplanation": true,
"includeGlossary": true,
"progressiveDisclosure": true
}
},
"formats": {
"detailed": {
"includeComments": true,
"showDataFlow": true,
"explainEachLine": true,
"includeContext": true
},
"summary": {
"keyPointsOnly": true,
"bulletFormat": true,
"highlightImportant": true
},
"interactive": {
"includeExamples": true,
"showVariations": true,
"includeExperiments": true,
"stepThroughExecution": true
},
"documentation": {
"formhighne": true,
"includeAPISignatures": true,
"showUsageExamples": true,
"includeBestPractices": true
}
},
"diagrams": {
"flowchart": {
"tool": "mermaid",
"showDecisionPoints": true,
"includeErrorPaths": true,
"colorCoding": true
},
"sequence": {
"tool": "mermaid",
"showAsyncOperations": true,
"includeTimings": false,
"showErrorScenarios": true
},
"architecture": {
"tool": "mermaid",
"showLayers": true,
"includeDependencies": true,
"showDataFlow": true
},
"dataFlow": {
"tool": "mermaid",
"showTransformations": true,
"includeValidation": true,
"showStoragePoints": true
}
},
"focus": {
"logic": {
"explainAlgorithms": true,
"showComplexity": true,
"includeEdgeCases": true
},
"architecture": {
"showPatterns": true,
"explainStructure": true,
"discussScalability": true
},
"performance": {
"identifyBottlenecks": true,
"suggestOptimizations": true,
"showBenchmarks": false
},
"security": {
"identifyVulnerabilities": true,
"explainMitigations": true,
"showBestPractices": true
}
},
"languages": {
"spanish": {
"useSpanishTerms": true,
"includeEnglishEquivalents": true,
"culturalContext": "latin-america"
},
"english": {
"variant": "us",
"technicalStyle": "modern"
}
}
}
```
## Command Output
### Code Analysis
```
π§ CLAUDE POWER - CODE EXPLANATION ANALYSIS
===========================================
π ANALYZED FILE:
src/services/PaymentProcessor.js (234 lines)
π AUTOMATIC ANALYSIS:
β’ Complexity: Medium (7.2/10)
β’ Detected patterns: Factory, Observer, Strategy
β’ Key concepts: Async programming, Error handling, State machine
β’ Business logic: Payment processing workflow
β’ Suggested audience: Intermediate developers
π IDENTIFIED ELEMENTS:
βββββββββββββββββββββββ¬ββββββββββ¬ββββββββββββββββββββββ
β Element β Count β Complexity β
βββββββββββββββββββββββΌββββββββββΌββββββββββββββββββββββ€
β Functions β 12 β Medium β
β Classes β 3 β High β
β Async Operations β 8 β Medium β
β Error Handlers β 6 β Low β
β Business Rules β 15 β High β
β Design Patterns β 3 β Medium β
βββββββββββββββββββββββ΄ββββββββββ΄ββββββββββββββββββββββ
π― ASPECTS TO EXPLAIN:
β’ Payment state machine workflow
β’ Error handling strategy
β’ Async operation coordination
β’ Security considerations
β’ Integration patterns
β’ Testing approaches
β±οΈ ESTIMATED READING TIME: 12-15 minutes
π₯ OPTIMAL AUDIENCE: Intermediate to Senior developers
```
### Generated Explanation
```
π COMPLETE EXPLANATION GENERATED:
================================
π DOCUMENT CREATED:
β’ src/services/PaymentProcessor.md (1,247 words)
β’ Diagrams included: 3 (flowchart, sequence, architecture)
β’ Practical examples: 8
β’ Concepts explained: 15
π― SECTIONS INCLUDED:
β
Purpose and responsibilities
β
Architecture and patterns used
β
Step-by-step data flow
β
Error handling and edge cases
β
Security considerations
β
Practical usage examples
β
Testing strategies
β
Possible improvements and optimizations
π QUALITY METRICS:
β’ Clarity: 9.2/10
β’ Completeness: 9.0/10
β’ Usefulness for onboarding: 9.5/10
β’ Technical accuracy: 9.8/10
π EDUCATIONAL FEEDBACK:
β’ Ideal for mid-level developers
β’ Contains concepts transferable to other projects
β’ Includes best practices and anti-patterns
β’ Facilitates future code reviews
```
### Interactive Diagrams
```
π¨ AUTOMATICALLY GENERATED DIAGRAMS:
======================================
π MAIN FLOWCHART:
β’ Shows the complete payment processing flow
β’ Includes decision points and error paths
β’ Color-coded by operation type
β’ Interactive links to detailed explanations
π SEQUENCE DIAGRAM:
β’ Interactions between services
β’ Timeouts and retries visualized
β’ Async operations clearly marked
β’ Error scenarios included
ποΈ ARCHITECTURE DIAGRAM:
β’ Dependencies between components
β’ Data flow between layers
β’ External service integrations
β’ Security boundaries marked
πΎ GENERATED FILES:
β’ payment-processor-flowchart.svg
β’ payment-processor-sequence.svg
β’ payment-processor-architecture.svg
β’ payment-processor-explanation.md
```
## Integrations with Tools
### VS Code Extension
```json
{
"commands": [
{
"command": "claude-power.explainCode",
"title": "Explain This Code",
"category": "Claude Power"
},
{
"command": "claude-power.explainFunction",
"title": "Explain Current Function",
"category": "Claude Power"
}
],
"menus": {
"editor/context": [
{
"command": "claude-power.explainCode",
"when": "editorHasSelection",
"group": "claude-power"
}
]
},
"keybindings": [
{
"command": "claude-power.explainCode",
"key": "ctrl+shift+e",
"when": "editorTextFocus"
}
]
}
```
### GitHub Integration
```yaml
name: Auto Documentation
on:
pull_request:
types: [opened, synchronize]
jobs:
explain-changes:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
token: ${{ secrets.GITHUB_TOKEN }}
- name: Get changed files
id: changes
run: |
git diff --name-only ${{ github.event.before }} ${{ github.sha }} > changed_files.txt
- name: Explain code changes
run: |
while read file; do
if [[ $file == *.js || $file == *.ts || $file == *.tsx ]]; then
npx claude-power explain-code "$file" \
--level=mixed-team \
--format=summary \
--output=markdown > "explanations/${file}.md"
fi
done < changed_files.txt
- name: Comment PR with explanations
uses: actions/github-script@v6
with:
script: |
const fs = require('fs');
const path = require('path');
const explanations = [];
const explanationsDir = 'explanations';
if (fs.existsSync(explanationsDir)) {
const files = fs.readdirSync(explanationsDir);
for (const file of files) {
const content = fs.readFileSync(path.join(explanationsDir, file), 'utf8');
const originalFile = file.replace('.md', '');
explanations.push(`
### π ${originalFile}
${content}
`);
}
}
if (explanations.length > 0) {
const comment = `
## π§ Code Explanation for Changes
${explanations.join('\n---\n')}
*Generated by Claude Power Explain Code*
`;
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: comment
});
}
```
*Part of the **Claude Power** ecosystem - Intelligently explained code* π§ π