stredne pokročilý

Dokumentácia kódu

DeepSeek v3.2 prompt pre detailné komentovanie kódu s vysvetlením funkcií, vstupov a výstupov

Programovanie
DeepSeek, ChatGPT, Claude
#deepseek#code#documentation#comments#programming

Dokumentácia kódu

DEEPSEEK v3.2 PROMPT

21. DOKUMENTÁCIA KÓDU

Prompt: „Pridaj detailné komentáre k tomuto kódu a vysvetli účel každej funkcie, vstupy a výstupy: [vložiť kód]."


ŠTRUKTÚRA DOKUMENTÁCIE

TYPY DOKUMENTÁCIE

  • Inline comments: Vysvetlenie komplexných častí
  • Function docstrings: Detailný popis funkcií
  • Module documentation: Popis celého modulu
  • Type hints: Typová anotácia
  • README instructions: Použitie a inštalácia

DOKUMENTAČNÉ ŠTANDARDY

  • Google Style: Google Python Style Guide
  • NumPy Style: NumPy/SciPy documentation
  • JSDoc: JavaScript documentation
  • Javadoc: Java documentation
  • Docstrings: Python PEP 257

PRÍKLAD: PYTHON FUNKCIE S DOKUMENTÁCIOU

PÔVODNÝ KÓD

def calc_total(items, tax_rate):
    total = 0
    for item in items:
        total += item['price'] * item['quantity']
    return total * (1 + tax_rate)

def find_user(users, user_id):
    for user in users:
        if user['id'] == user_id:
            return user
    return None

def process_data(data):
    result = []
    for item in data:
        if item['active']:
            result.append({
                'name': item['name'],
                'value': item['value'] * 2
            })
    return result

DOKUMENTOVANÝ KÓD

from typing import List, Dict, Optional, Any

def calculate_total_price(items: List[Dict[str, Any]], tax_rate: float) -> float:
    """
    Calculate the total price of items including tax.

    This function computes the total cost of a list of items by multiplying
    the price by quantity for each item, then applying a tax rate to the
    subtotal.

    Args:
        items (List[Dict[str, Any]]): List of items with 'price' and 'quantity' keys.
            Each item should be a dictionary with:
            - 'price' (float): Unit price of the item
            - 'quantity' (int): Number of units

        tax_rate (float): Tax rate as a decimal (e.g., 0.2 for 20% tax).
            Should be between 0 and 1.

    Returns:
        float: Total price including tax, rounded to 2 decimal places.

    Raises:
        ValueError: If tax_rate is negative or items list is empty.
        TypeError: If items don't contain required keys or have invalid types.

    Example:
        >>> items = [{'price': 10.0, 'quantity': 2}, {'price': 5.0, 'quantity': 3}]
        >>> calculate_total_price(items, 0.2)
        48.0

    Note:
        - Function rounds the result to 2 decimal places for currency formatting
        - Empty items list raises ValueError to prevent division by zero
        - Negative tax rates are not allowed
    """
    # Input validation
    if not items:
        raise ValueError("Items list cannot be empty")

    if tax_rate < 0:
        raise ValueError("Tax rate cannot be negative")

    # Calculate subtotal by summing price * quantity for each item
    subtotal = 0.0
    for item in items:
        # Validate item structure
        if not isinstance(item, dict):
            raise TypeError("Each item must be a dictionary")

        if 'price' not in item or 'quantity' not in item:
            raise TypeError("Each item must have 'price' and 'quantity' keys")

        if not isinstance(item['price'], (int, float)) or not isinstance(item['quantity'], int):
            raise TypeError("Price must be numeric and quantity must be integer")

        # Calculate item total and add to subtotal
        item_total = item['price'] * item['quantity']
        subtotal += item_total

    # Apply tax and round to 2 decimal places
    total_with_tax = subtotal * (1 + tax_rate)
    return round(total_with_tax, 2)


def find_user_by_id(users: List[Dict[str, Any]], user_id: int) -> Optional[Dict[str, Any]]:
    """
    Find a user in a list by their unique ID.

    Searches through a list of user dictionaries and returns the first user
    matching the specified ID. If no user is found, returns None.

    Args:
        users (List[Dict[str, Any]]): List of user dictionaries.
            Each user dictionary should contain at least an 'id' key.

        user_id (int): The unique identifier to search for.
            Should be a positive integer.

    Returns:
        Optional[Dict[str, Any]]: User dictionary if found, None otherwise.
            Returns the complete user object with all user data.

    Raises:
        ValueError: If user_id is negative.
        TypeError: If users list contains non-dictionary items.

    Example:
        >>> users = [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}]
        >>> find_user_by_id(users, 1)
        {'id': 1, 'name': 'Alice'}
        >>> find_user_by_id(users, 3) is None
        True

    Note:
        - Function returns the first matching user (IDs should be unique)
        - Performance: O(n) time complexity for linear search
        - Consider using a dictionary with ID as key for better performance
    """
    # Input validation
    if user_id < 0:
        raise ValueError("User ID cannot be negative")

    # Linear search through users list
    for user in users:
        # Validate user structure
        if not isinstance(user, dict):
            raise TypeError("Each user must be a dictionary")

        if 'id' not in user:
            raise TypeError("Each user must have an 'id' key")

        # Check if this user matches the requested ID
        if user['id'] == user_id:
            return user

    # No user found with matching ID
    return None


def process_active_data(data: List[Dict[str, Any]]) -> List[Dict[str, str]]:
    """
    Process data by filtering active items and transforming their values.

    This function filters a list of data dictionaries to only include items
    where 'active' is True, then transforms each active item by doubling
    the 'value' field and creating a new dictionary with 'name' and 'value'.

    Args:
        data (List[Dict[str, Any]]): List of data dictionaries.
            Each dictionary should contain:
            - 'active' (bool): Whether the item is active
            - 'name' (str): Name of the item
            - 'value' (numeric): Value to be processed

    Returns:
        List[Dict[str, str]]: List of processed active items.
            Each item in the returned list contains:
            - 'name' (str): Original item name
            - 'value' (str): Doubled original value as string

    Raises:
        TypeError: If data structure is invalid or contains wrong types.

    Example:
        >>> data = [
        ...     {'active': True, 'name': 'Item1', 'value': 10},
        ...     {'active': False, 'name': 'Item2', 'value': 20},
        ...     {'active': True, 'name': 'Item3', 'value': 5}
        ... ]
        >>> process_active_data(data)
        [{'name': 'Item1', 'value': '20'}, {'name': 'Item3', 'value': '10'}]

    Note:
        - Inactive items are completely ignored
        - Value is converted to string in the output
        - Function assumes 'value' can be multiplied by 2
    """
    processed_items = []

    for item in data:
        # Validate item structure
        if not isinstance(item, dict):
            raise TypeError("Each item must be a dictionary")

        # Check required keys
        required_keys = ['active', 'name', 'value']
        for key in required_keys:
            if key not in item:
                raise TypeError(f"Each item must have '{key}' key")

        # Validate data types
        if not isinstance(item['active'], bool):
            raise TypeError("'active' must be a boolean")

        if not isinstance(item['name'], str):
            raise TypeError("'name' must be a string")

        if not isinstance(item['value'], (int, float)):
            raise TypeError("'value' must be numeric")

        # Process only active items
        if item['active']:
            # Create new dictionary with transformed data
            processed_item = {
                'name': item['name'],
                'value': str(item['value'] * 2)  # Double value and convert to string
            }
            processed_items.append(processed_item)

    return processed_items

PRÍKLAD PRE JAVASCRIPT

PÔVODNÝ KÓD

function calcDiscount(price, discount) {
  return price * (1 - discount);
}

function validateEmail(email) {
  return email.includes("@") && email.includes(".");
}

function formatCurrency(amount) {
  return "$" + amount.toFixed(2);
}

DOKUMENTOVANÝ KÓD

/**
 * Calculate discounted price.
 *
 * @param {number} price - Original price of the item. Must be positive.
 * @param {number} discount - Discount rate as decimal (0.2 for 20%).
 *                           Must be between 0 and 1.
 * @returns {number} Discounted price rounded to 2 decimal places.
 * @throws {Error} If price is negative or discount is invalid.
 *
 * @example
 * calcDiscount(100, 0.2); // Returns 80
 * calcDiscount(50, 0.1); // Returns 45
 */
function calculateDiscountedPrice(price, discount) {
  // Input validation
  if (typeof price !== "number" || price < 0) {
    throw new Error("Price must be a positive number");
  }

  if (typeof discount !== "number" || discount < 0 || discount > 1) {
    throw new Error("Discount must be a number between 0 and 1");
  }

  // Calculate discounted price
  const discountedPrice = price * (1 - discount);

  // Round to 2 decimal places for currency
  return Math.round(discountedPrice * 100) / 100;
}

/**
 * Validate email address format.
 *
 * @param {string} email - Email address to validate.
 * @returns {boolean} True if email appears valid, false otherwise.
 *
 * @description
 * This function performs basic email validation by checking for the presence
 * of '@' symbol and at least one '.' after the '@'. This is a simple
 * validation and may not catch all invalid email formats.
 *
 * @example
 * validateEmail('user@example.com'); // Returns true
 * validateEmail('invalid-email'); // Returns false
 */
function validateEmailAddress(email) {
  // Input validation
  if (typeof email !== "string") {
    return false;
  }

  // Basic email validation
  const hasAtSymbol = email.includes("@");
  const hasDotAfterAt = email.split("@")[1]?.includes(".") || false;

  return hasAtSymbol && hasDotAfterAt;
}

/**
 * Format amount as currency string.
 *
 * @param {number} amount - Numeric amount to format.
 * @param {string} [currency='$'] - Currency symbol to use.
 * @returns {string} Formatted currency string.
 * @throws {Error} If amount is not a valid number.
 *
 * @example
 * formatCurrency(1234.5); // Returns '$1,234.50'
 * formatCurrency(99.99, '€'); // Returns '€99.99'
 */
function formatCurrency(amount, currency = "$") {
  // Input validation
  if (typeof amount !== "number" || isNaN(amount)) {
    throw new Error("Amount must be a valid number");
  }

  if (typeof currency !== "string") {
    throw new Error("Currency must be a string");
  }

  // Format with thousands separator and 2 decimal places
  const formattedAmount = amount.toLocaleString("en-US", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });

  return `${currency}${formattedAmount}`;
}

DOKUMENTAČNÉ TEMPLATES

PYTHON DOCSTRING TEMPLATE

def function_name(param1: type1, param2: type2) -> return_type:
    """
    Brief description of the function.

    Detailed description explaining what the function does, its purpose,
    and any important implementation details.

    Args:
        param1 (type1): Description of parameter 1.
            Include any constraints, expected format, or default values.
        param2 (type2): Description of parameter 2.
            Explain any special requirements or edge cases.

    Returns:
        return_type: Description of what the function returns.
            Include format, possible values, and any important notes.

    Raises:
        ExceptionType: Description of when this exception is raised.
        AnotherException: Description of another exception condition.

    Example:
        >>> function_name(value1, value2)
        Expected output or result

    Note:
        Any additional notes, warnings, or implementation details.
        Include performance considerations if relevant.
    """
    pass

JAVASCRIPT JSDOC TEMPLATE

/**
 * Brief description of the function.
 *
 * @param {type} paramName - Description of the parameter.
 * @param {type} [optionalParam] - Description of optional parameter.
 * @returns {type} Description of return value.
 * @throws {ErrorType} Description of when error is thrown.
 *
 * @example
 * // Example usage
 * const result = functionName(param1, param2);
 * console.log(result); // Expected output
 *
 * @description
 * Detailed description of what the function does, including
 * any important implementation details or considerations.
 */
function functionName(paramName, optionalParam = defaultValue) {
  // Implementation
}

BEST PRACTICES

KOMENTÁROVANIE PRINCÍPY

  • Komentuj preč, nie čo: Vysvetliť dôvod, nie zjavné
  • Buď konkrétny: Presné popisy a príklady
  • Konzistencia: Jednotný štýl v celom projekte
  • Aktualizácia: Udržujte komentáre aktuálne

ČO KOMENTOVAŤ

  • Komplexná logika: Vysvetliť zložité algoritmy
  • Business logika: Prečo sa robí určitá vec
  • Edge cases: Špeciálne situácie a výnimky
  • API rozhrania: Ako používať funkcie
  • Dôležité premenné: Prečo existuje dôležitá premenná

ČO NEKOMENTOVAŤ

  • Zjavné veci: x = x + 1 nepotrebuje komentár
  • Zlý kód: Oprav kód namiesto komentovania
  • Zastaralé komentáre: Vymažte nepoužívané komentáre
  • Osobné poznámky: Použite TODO/FIXME s dátumom

NÁSTROJE PRE DOKUMENTÁCIU

PYTHON

  • Sphinx: Automatická generácia dokumentácie
  • pydoc: Built-in documentation tool
  • pdoc: Simple documentation generator
  • MkDocs: Static site generator

JAVASCRIPT

  • JSDoc: Documentation generator
  • TypeDoc: TypeScript documentation
  • ESDoc: JavaScript documentation
  • GitBook: Book-style documentation

VŠEOBECNÉ

  • GitHub Pages: Free hosting for docs
  • Read the Docs: Documentation hosting
  • Confluence: Team documentation
  • Notion: Modern documentation platform

AUTOMATICKÁ DOKUMENTÁCIA

PYTHON SEDGE

# setup.py
from sphinx.setup_command import SetupCommand

setup(
    name='my-package',
    version='1.0.0',
    cmdclass={
        'build_sphinx': SetupCommand
    }
)

JAVASCRIPT PACKAGE.JSON

{
  "scripts": {
    "docs": "jsdoc -c jsdoc.json src/*.js",
    "docs-serve": "http-server docs -p 8080"
  },
  "devDependencies": {
    "jsdoc": "^3.6.0",
    "http-server": "^0.12.0"
  }
}

REVIEW PROCES

CODE REVIEW CHECKLIST

📋 DOKUMENTÁCIA REVIEW:
□ Má každá funkcia docstring?
□ Sú parametre zdokumentované?
□ Sú návratové hodnoty popísané?
□ Sú výnimky zdokumentované?
□ Sú príklady použitia?
□ Sú typové anotácie správne?
□ Je jazyk konzistentný?
□ Sú komentáre užitočné?

🔥 KVALITA CHECKLIST:
□ Je dokumentácia presná?
□ Je aktuálna s kódom?
□ Je zrozumiteľná pre nových vývojárov?
□ Pokrýva edge cases?
□ Má dostatočné príklady?

MAINTENANCE

📅 PRavidelná údržba:
• Týždenné: Check pre new functions
• Mesačné: Review documentation quality
• Kvartálne: Update examples and tutorials
• Ročné: Complete documentation audit

Podobné prompty

Programovanie

Ďalší prompt v kategórii

Preskúmajte ďalšie prompty v rovnakej kategórii.

Zobraziť viac →
Odporúčané

Najlepšie prompty

Objavte najpopulárnejšie a najúčinnejšie prompty.

Preskúmať všetky →