Skip to content

Code Style Guide

Standards and best practices for Certana codebase.

Python (Backend)

PEP 8 Compliance

  • Line length: Maximum 100 characters
  • Indentation: 4 spaces (not tabs)
  • Imports: Alphabetical, grouped (stdlib, third-party, local)

Naming Conventions

# Classes: PascalCase
class AssetService:
    pass

# Functions/methods: snake_case
async def verify_image(image: np.ndarray) -> bool:
    pass

# Constants: UPPER_SNAKE_CASE
MAX_FILE_SIZE_BYTES = 100_000_000
SUPPORTED_FORMATS = ["jpeg", "png", "webp"]

# Private: leading underscore
def _internal_helper(value: int) -> int:
    pass

Type Hints

# Always use type hints
def process_image(
    image: np.ndarray,
    compression_level: int = 85
) -> Tuple[np.ndarray, dict]:
    """Process image with optional compression."""
    ...

# For complex types, use typing
from typing import Optional, List, Dict, Union

async def query_assets(
    organization_id: UUID,
    filters: Optional[Dict[str, Any]] = None
) -> List[Asset]:
    pass

Docstrings

def calculate_similarity(
    embedding1: np.ndarray,
    embedding2: np.ndarray
) -> float:
    """
    Calculate cosine similarity between two embeddings.

    Args:
        embedding1: First embedding vector
        embedding2: Second embedding vector

    Returns:
        Similarity score between 0 and 1

    Raises:
        ValueError: If embeddings have different dimensions

    Examples:
        >>> emb1 = np.array([1, 2, 3])
        >>> emb2 = np.array([4, 5, 6])
        >>> similarity = calculate_similarity(emb1, emb2)
        >>> 0 <= similarity <= 1
        True
    """
    if len(embedding1) != len(embedding2):
        raise ValueError("Embedding dimensions must match")

    # Calculate similarity
    ...

Code Organization

# Order in modules:
# 1. Module docstring
# 2. Imports
# 3. Constants
# 4. Classes
# 5. Functions
# 6. Main block

"""Module docstring explaining purpose."""

from typing import Optional
import logging

logger = logging.getLogger(__name__)

# Constants
DEFAULT_TIMEOUT = 30

# Classes
class MyService:
    pass

# Functions
def my_function() -> None:
    pass

# Main
if __name__ == "__main__":
    ...

Formatting

# Format with Black
black src/

# Sort imports
isort src/

# Type checking
mypy src/

# Lint with Flake8
flake8 src/

TypeScript (Frontend & Extension)

Naming Conventions

// Interfaces: PascalCase
interface VerificationResult {
  verdict: string;
  confidence: number;
}

// Types: PascalCase
type AssetStatus = 'pending' | 'completed' | 'failed';

// Functions: camelCase
function verifyImage(image: File): Promise<VerificationResult> {
  // ...
}

// Constants: UPPER_SNAKE_CASE
const MAX_FILE_SIZE_MB = 100;
const API_ENDPOINTS = {
  VERIFY: '/v1/verify',
  ASSETS: '/v1/assets',
};

// Components: PascalCase
export const ImageVerifier: React.FC<Props> = (props) => {
  // ...
};

// Private functions: leading underscore
function _internalHelper(): void {
  // ...
}

Type Definitions

// Always define types
interface Asset {
  id: string;
  title: string;
  fileSize: number;
  createdAt: Date;
}

type ApiResponse<T> = {
  data: T;
  message: string;
  timestamp: Date;
};

// Use strict null checks
async function getAsset(id: string): Promise<Asset | null> {
  // ...
}

React Best Practices

// Use functional components
export const MyComponent: React.FC<Props> = ({ prop1, prop2 }) => {
  // Use hooks
  const [state, setState] = useState<string>('');
  const [loading, setLoading] = useAsync(() => fetchData());

  // Use useCallback for memoization
  const handleClick = useCallback(() => {
    // ...
  }, [dependencies]);

  return (
    // JSX
  );
};

// Memoize expensive components
export const MemoizedComponent = memo(MyComponent);

Formatting

# Format with Prettier
npx prettier --write src/

# Lint with ESLint
npm run lint

# Type check
npx tsc --noEmit

Vue.js (Extension Components)

Component Structure

<template>
  <div class="component">
    <!-- Template content -->
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed } from 'vue';

export default defineComponent({
  name: 'MyComponent',
  props: {
    title: String,
  },
  emits: ['change'],
  setup(props, { emit }) {
    const state = ref<string>('');

    const computed_value = computed(() => {
      return state.value.toUpperCase();
    });

    return {
      state,
      computed_value,
    };
  },
});
</script>

<style scoped>
.component {
  /* Scoped styles */
}
</style>

Comments & Documentation

Python Comments

# Good: Clear, concise comments
# Calculate embedding distance
distance = np.linalg.norm(emb1 - emb2)

# Bad: Redundant comments
x = 5  # Set x to 5

# Use docstrings, not just comments
def important_function() -> None:
    """Explain what the function does."""

TypeScript Comments

// Good: JSDoc for public APIs
/**
 * Verify image authenticity
 * @param image - Image file to verify
 * @returns Verification result
 * @throws {Error} If verification fails
 */
function verifyImage(image: File): Promise<VerificationResult> {
  // Implementation
}

// Explain complex logic
// Using iterative approach for better performance

Error Handling

Python

# Create domain-specific exceptions
class CertanaException(Exception):
    """Base Certana exception"""
    pass

class AssetNotFoundError(CertanaException):
    """Asset not found in database"""
    pass

# Use context managers
try:
    result = await verify_image(file)
except AssetNotFoundError as e:
    logger.error("Asset not found", exc_info=True)
    raise HTTPException(status_code=404) from e
except Exception as e:
    logger.error("Unexpected error", exc_info=True)
    raise

TypeScript

// Define error interfaces
interface ApiError {
  code: string;
  message: string;
  details?: Record<string, any>;
}

// Use try-catch with types
try {
  await verifyImage(file);
} catch (error) {
  if (error instanceof ApiError) {
    handleApiError(error);
  } else if (error instanceof Error) {
    console.error(error.message);
  }
}

Testing

Python Tests

import pytest
from unittest.mock import patch, AsyncMock

@pytest.mark.asyncio
async def test_verify_image_success(mock_service):
    """Test successful image verification"""
    # Arrange
    image = create_test_image()

    # Act
    result = await mock_service.verify_image(image)

    # Assert
    assert result.verdict == 'authentic'
    assert result.confidence > 0.8

TypeScript Tests

import { describe, it, expect, beforeEach } from 'vitest';

describe('ImageVerifier', () => {
  let verifier: ImageVerifier;

  beforeEach(() => {
    verifier = new ImageVerifier();
  });

  it('should verify authentic image', async () => {
    // Arrange
    const image = createTestImage();

    // Act
    const result = await verifier.verify(image);

    // Assert
    expect(result.verdict).toBe('authentic');
    expect(result.confidence).toBeGreaterThan(0.8);
  });
});

Next Steps