Files
thrillwiki_django_no_react/.clinerules/code-complexity-management.md

2.3 KiB

Brief overview

Guidelines for managing code complexity and maintaining clean, maintainable code in Django projects. These rules focus on reducing cognitive complexity, improving code organization, and following best practices for refactoring complex methods.

Cognitive complexity management

  • Always break down methods with high cognitive complexity (>15) into smaller, focused helper methods
  • Extract logical operations into separate methods with descriptive names
  • Use single responsibility principle - each method should have one clear purpose
  • Prefer composition over deeply nested conditional logic
  • When refactoring complex methods, maintain original functionality while improving structure

Method extraction patterns

  • Create helper methods for parameter parsing and validation
  • Separate data retrieval logic from serialization logic
  • Extract cache operations into dedicated methods
  • Use descriptive method names that clearly indicate their purpose (e.g., _serialize_park_data, _get_parks_data)
  • Keep helper methods focused and avoid creating new complexity within them

Error handling and type safety

  • Always handle None values explicitly to avoid type errors
  • Use proper type annotations, including union types (e.g., Polygon | None)
  • Implement fallback mechanisms for operations that may not be available in all environments
  • Validate input parameters before processing to prevent runtime errors
  • Use getattr() with defaults when accessing potentially missing attributes

Django API view organization

  • Structure API views with clear separation between parameter handling, business logic, and response building
  • Use helper methods to reduce the main method complexity while preserving readability
  • Maintain consistent error response formats across all endpoints
  • Implement proper caching strategies with appropriate fallbacks
  • Follow DRF patterns for serialization and response construction

Refactoring approach

  • When addressing SonarQube or linting warnings, focus on structural improvements rather than quick fixes
  • Preserve all original functionality during refactoring
  • Test edge cases and error conditions after complexity reduction
  • Maintain API contracts and response formats
  • Document complex business logic within helper methods when necessary