Skip to content

Code Style

Dragon edited this page Dec 23, 2025 · 2 revisions

📐 NaviDuck Code Style

Last updated: 12/22/2025

🎯 Quick Reference Card

Core Principles

┌─────────────────────────────────────────────┐
│            Code Style Checklist             │
├─────────────────────────────────────────────┤
│ ✅ PEP 8 compliant                         │
│ ✅ Clear, descriptive names                │
│ ✅ Comprehensive docstrings                │
│ ✅ Type hints (optional but recommended)   │
│ ✅ Consistent error handling               │
│ ✅ Modular, single-responsibility design   │
│ ✅ Test-driven approach                    │
└─────────────────────────────────────────────┘

📝 Naming Conventions

File & Directory Names

  • Snake case: search_manager.py, browser_state.py
  • Descriptive: Clearly indicate purpose
  • Short but meaningful: Avoid abbreviations

Python Elements

# Variables & functions: snake_case
search_results = []
def parse_html_content(): ...

# Constants: UPPER_SNAKE_CASE
MAX_RESULTS = 10
DEFAULT_ENGINE = "brave"

# Classes: PascalCase
class SearchManager: ...
class BrowserState: ...

# Private: _leading_underscore
def _internal_helper(): ...

📁 Code Organization

Standard File Structure

"""
Module docstring - What this module does
"""

# 1. Standard library imports
import json
import re
import time
from typing import List, Dict, Optional

# 2. Third-party imports
import requests
from colorama import Fore

# 3. Constants
MAX_RESULTS = 10
TIMEOUT = 10

# 4. Classes
class MainClass:
    """Class docstring"""
    pass

# 5. Functions
def helper_function():
    """Function docstring"""
    pass

# 6. Main guard
if __name__ == "__main__":
    pass

Import Order

  1. Standard library
  2. Third-party packages
  3. Local modules (if we had them)

📚 Documentation Standards

Module & Class Docstrings

"""
Search Manager Module

Handles web search across multiple engines, parsing results,
and implementing fallback strategies.
"""

class SearchManager:
    """
    Main search manager class.
    
    Attributes:
        state (BrowserState): Current browser state
        network (NetworkManager): Network handler
    """

Function Docstrings

def search(self, query, engine=None):
    """
    Search the web for a query.
    
    Args:
        query (str): Search query
        engine (str, optional): Engine to use
    
    Returns:
        List[dict]: Search results
    
    Raises:
        SearchError: If search fails
        NetworkError: If connection fails
    
    Examples:
        >>> search("python tutorial")
        [{'title': 'Python Tutorial', ...}]
    """

🎨 Formatting Rules

PEP 8 Compliance

# ✅ Good spacing
def function_name(arg1, arg2=default):
    result = []
    for item in items:
        if condition:
            result.append(item)
    return result

# ❌ Avoid
def badFunction(arg1,arg2=default):
    result=[]
    for item in items:
        if condition:result.append(item)
    return result

Line Length & Breaking

  • Max 79 characters per line
  • Break long lines at logical points
  • Use parentheses for continued lines

🔧 Error Handling

Custom Exceptions

class NaviDuckError(Exception):
    """Base exception."""

class SearchError(NaviDuckError):
    """Search-related errors."""

class NetworkError(NaviDuckError):
    """Network-related errors."""

Graceful Error Messages

def handle_error(self, error):
    if isinstance(error, NetworkError):
        print(f"{Colors.ERROR}❌ Network error. Check connection.{Colors.RESET}")
        print(f"{Colors.INFO}Try: 1. Check internet 2. Use Tor{Colors.RESET}")

🧪 Testing Standards

Test Structure

# tests/test_search_manager.py
import pytest

class TestSearchManager:
    def setup_method(self):
        """Setup before each test."""
        self.manager = SearchManager()
    
    def test_valid_search(self):
        """Test search with valid query."""
        results = self.manager.search("test")
        assert len(results) > 0
    
    @pytest.mark.parametrize("engine", ["brave", "ddg", "google"])
    def test_engine_parsing(self, engine):
        """Test different search engines."""
        results = self.manager.search("test", engine=engine)
        assert isinstance(results, list)

🔄 Git & Commit Standards

Commit Message Format

<type>[optional scope]: <description>

[optional body]

[optional footer]

Commit Types

  • feat: New feature
  • fix: Bug fix
  • docs: Documentation
  • style: Formatting
  • refactor: Code refactoring
  • test: Tests
  • chore: Maintenance

Examples

git commit -m "feat: add Brave search engine"
git commit -m "fix: correct CAPTCHA detection logic"
git commit -m "docs: update search guide"

🚫 Anti-Patterns to Avoid

Don't Do This

# ❌ Vague names
x = get_data()  
a = process(x)

# ❌ Magic numbers
time.sleep(5)  # What does 5 mean?

# ❌ Overly complex one-liners
result = [x for x in data if x > 0 and x < 100 and x % 2 == 0]

# ❌ Ignoring errors
try:
    do_something()
except:
    pass  # Silent failure!

Do This Instead

# ✅ Clear names
search_results = fetch_search_results()
processed_results = filter_valid_results(search_results)

# ✅ Named constants
SEARCH_TIMEOUT = 5
time.sleep(SEARCH_TIMEOUT)

# ✅ Clear, readable logic
valid_results = [
    result for result in data 
    if 0 < result < 100 and result % 2 == 0
]

# ✅ Proper error handling
try:
    do_something()
except SpecificError as e:
    logger.error(f"Operation failed: {e}")
    handle_error_gracefully()

📊 Quick Checklist

Before Submitting Code

  • Code follows PEP 8
  • Descriptive variable/function names
  • Comprehensive docstrings
  • Error handling implemented
  • Tests written and passing
  • No commented-out debug code
  • Documentation updated
  • Commit message follows conventions

Code Review Checklist

  • Single responsibility per function/class
  • No duplicated code
  • Clear and maintainable
  • Edge cases handled
  • Performance considered
  • Security implications reviewed

🎨 Style Tools

Automated Formatting

# Install tools
pip install black flake8 mypy

# Format code
black naviduck.py

# Check style
flake8 naviduck.py

# Type checking (optional)
mypy naviduck.py

Editor Configuration

// .vscode/settings.json
{
  "python.formatting.provider": "black",
  "python.linting.enabled": true,
  "python.linting.flake8Enabled": true,
  "python.linting.mypyEnabled": true
}

📈 Quality Metrics

Target Standards

  • Test Coverage: > 80%
  • Code Complexity: Cyclomatic complexity < 10
  • Documentation: 100% of public APIs documented
  • Duplication: < 3% duplicated code
  • Maintainability: A rating on CodeClimate

🎯 TL;DR - The Golden Rules

  1. Be Clear: Write code for the next developer
  2. Be Consistent: Follow existing patterns
  3. Be Complete: Document and test thoroughly
  4. Be Considerate: Handle errors gracefully
  5. Be Clean: Keep it simple and maintainable

Last updated: 12/22/2025
Code Style Summary version: 2.0

Remember: Good code is like a good joke - it needs no explanation, but documentation helps! 😄

Clone this wiki locally