code-comment-generator
Generates meaningful comments and documentation for code to improve maintenance and readability. Use when adding documentation to Python or Java code, including function/method docstrings, class documentation, inline explanations for complex logic, and code annotations (TODO, FIXME). Analyzes existing comment style in the codebase to match conventions. Produces clear, concise comments that explain the "why" not just the "what", following best practices for each language.
git clone --depth 1 https://github.com/ArabelaTso/Skills-4-SE /tmp/code-comment-generator && cp -r /tmp/code-comment-generator/skills/code-comment-generator ~/.claude/skills/code-comment-generatorSKILL.md
# Code Comment Generator
Generate meaningful, maintainable comments and documentation for your code.
## Core Capabilities
This skill helps you create effective code documentation by:
1. **Analyzing code context** - Understanding what the code does and why
2. **Matching existing style** - Following comment conventions in your codebase
3. **Writing clear documentation** - Creating function/method/class documentation
4. **Adding inline explanations** - Explaining complex logic and algorithms
5. **Inserting code annotations** - Adding TODO, FIXME, and optimization notes
## Comment Generation Workflow
### Step 1: Analyze Existing Comment Style
Before generating comments, examine the codebase to match style:
**Look for:**
- Documentation format (docstrings, Javadoc, etc.)
- Comment verbosity level (detailed vs. concise)
- Naming conventions and terminology
- Use of examples in documentation
- Type annotation style
**Python Example - Analyze Existing Style:**
```python
# If existing code uses this pattern:
def get_user(user_id: int) -> User:
"""
Retrieve user by ID.
Args:
user_id: Unique identifier for the user
Returns:
User object if found
Raises:
UserNotFoundError: If user doesn't exist
"""
return db.query(User).get(user_id)
```
**Style Identified:**
- Google-style docstrings
- Type hints in signature
- Concise summary line
- Args/Returns/Raises sections
- No examples included
**Java Example - Analyze Existing Style:**
```java
// If existing code uses this pattern:
/**
* Retrieves a user by their unique identifier.
*
* @param userId the unique identifier for the user
* @return the User object if found
* @throws UserNotFoundException if no user exists with the given ID
*/
public User getUser(int userId) throws UserNotFoundException {
return database.findUser(userId);
}
```
**Style Identified:**
- Standard Javadoc format
- Brief summary sentence
- @param, @return, @throws tags
- Formal tone
- No code examples
### Step 2: Understand the Code
Analyze the code to understand what to document:
**For Functions/Methods:**
- What does it do? (purpose)
- Why does it exist? (intent)
- What are the parameters?
- What does it return?
- What exceptions/errors can it raise?
- Are there side effects?
- Are there important preconditions or postconditions?
**For Classes:**
- What is the class responsible for?
- What design pattern does it implement?
- How should it be used?
- What are the key methods?
- Are there usage examples needed?
**For Complex Logic:**
- What algorithm is being used?
- Why this approach vs. alternatives?
- What are the edge cases?
- Are there performance considerations?
### Step 3: Write Function/Method Documentation
Generate documentation that explains purpose and usage.
**Python Example:**
```python
# Before (no comments)
def calculate_shipping_cost(items, destination, method):
base = sum(item.weight * 0.5 for item in items)
if destination.international:
base *= 1.5
if method == 'express':
base *= 2
return base + 5
# After (with documentation)
def calculate_shipping_cost(items: List[Item], destination: Address, method: str) -> float:
"""
Calculate total shipping cost based on items, destination, and shipping method.
The base cost is calculated from item weights ($0.50 per unit). International
shipping adds a 50% surcharge, and express shipping doubles the cost. A flat
$5 handling fee is added to all orders.
Args:
items: List of items to ship, each with a weight attribute
destination: Shipping address with international flag
method: Shipping method ('standard' or 'express')
Returns:
Total shipping cost in USD
Example:
>>> items = [Item(weight=2), Item(weight=3)]
>>> addr = Address(country='USA', international=False)
>>> calculate_shipping_cost(items, addr, 'standard')
7.5
"""
# Calculate base cost from item weights
base = sum(item.weight * 0.5 for item in items)
# Apply international surcharge if applicable
if destination.international:
base *= 1.5
# Double cost for express shipping
if method == 'express':
base *= 2
# Add handling fee
return base + 5
```
**Java Example:**
```java
// Before (no comments)
public double calculateShippingCost(List<Item> items, Address destination, String method) {
double base = items.stream()
.mapToDouble(item -> item.getWeight() * 0.5)
.sum();
if (destination.isInternational()) {
base *= 1.5;
}
if ("express".equals(method)) {
base *= 2;
}
return base + 5;
}
// After (with documentation)
/**
* Calculates the total shipping cost based on items, destination, and shipping method.
*
* <p>The base cost is calculated from item weights ($0.50 per unit). International
* shipping adds a 50% surcharge, and express shipping doubles the cost. A flat
* $5 handling fee is added to all orders.
*
* @param items the list of items to ship, each with a weight
* @param destination the shipping address with international flag
* @param method the shipping method ("standard" or "express")
* @return the total shipping cost in USD
* @throws IllegalArgumentException if method is not "standard" or "express"
*/
public double calculateShippingCost(List<Item> items, Address destination, String method) {
// Calculate base cost from item weights ($0.50 per unit)
double base = items.stream()
.mapToDouble(item -> item.getWeight() * 0.5)
.sum();
// Apply 50% surcharge for international shipping
if (destination.isInternational()) {
base *= 1.5;
}
// Double the cost for express shipping
if ("express".equals(method)) {
base *= 2;
}
// Add $5 handling fee
return base + 5;
}
```
### Step 4: Add Inline Explanations
Add comments for complex or non-obvious code sections.
**When to AApplies abstract interpretation using different abstract domains (intervals, octagons, polyhedra, sign, congruence) to statically analyze program variables and infer invariants, value ranges, and relationships. Use when analyzing program properties, inferring loop invariants, detecting potential errors, or understanding variable relationships through static analysis.
Uses abstract interpretation to automatically infer loop invariants, function preconditions, and postconditions for formal verification. Generates invariants that capture program behavior and support correctness proofs in Dafny, Isabelle, Coq, and other verification systems. Use when adding formal specifications to code, generating verification conditions, inferring contracts for functions, or discovering loop invariants for proofs.
Performs abstract interpretation over source code to infer possible program states, variable ranges, and data properties without executing the program. Reports potential runtime errors including out-of-bounds accesses, null dereferences, type inconsistencies, division by zero, and integer overflows. Use when analyzing code for potential runtime errors, performing static analysis, checking safety properties, or verifying program behavior without execution.
Performs abstract interpretation to produce summarized execution traces and high-level program behavior representations. Highlights key control flow paths, variable relationships, loop invariants, function summaries, and potential runtime states using abstract domains (intervals, signs, nullness, etc.). Use when analyzing program behavior, understanding execution paths, computing loop invariants, tracking variable ranges, detecting potential runtime errors, or generating program summaries without concrete execution.
Create ACSL (ANSI/ISO C Specification Language) formal annotations for C/C++ programs. Use this skill when working with formal verification, adding function contracts (requires/ensures), loop invariants, assertions, memory safety annotations, or any ACSL specifications. Supports Frama-C verification and generates comprehensive formal specifications for C/C++ code.
CLI-based browser automation with persistent page state using ref-based element interaction. Use when users ask to navigate websites, interact with web pages, fill forms, take screenshots, test web applications, or extract information from web pages.
Detects and analyzes ambiguous language in software requirements and user stories. Use when reviewing requirements documents, user stories, specifications, or any software requirement text to identify vague quantifiers, unclear scope, undefined terms, missing edge cases, subjective language, and incomplete specifications. Provides detailed analysis with clarifying questions and suggested improvements.
Design and review APIs with suggestions for endpoints, parameters, return types, and best practices. Use when designing new APIs from requirements, reviewing existing API designs, generating API documentation, or getting implementation guidance. Supports REST APIs with focus on endpoint structure, request/response schemas, authentication, pagination, filtering, versioning, and OpenAPI specifications. Triggers when users ask to design, review, document, or improve APIs.