Best Practices
Code Organization

Code Organization

Best practices for organizing code in HiveForge.

File Structure Principles

1. Feature-Based Organization

Group files by feature, not by type:

Good:
src/features/
  auth/
    AuthForm.tsx
    useAuth.ts
    auth.api.ts
    auth.types.ts

Bad:
src/
  components/AuthForm.tsx
  hooks/useAuth.ts
  api/auth.ts
  types/auth.ts

2. Colocation

Keep related files together:

// Component with test and styles
components/
  Button/
    Button.tsx
    Button.test.tsx
    Button.module.css
    index.ts

3. Clear Exports

Use index files for clean imports:

// components/index.ts
export { Button } from './Button'
export { Input } from './Input'
export { Card } from './Card'
 
// Usage
import { Button, Input } from '@/components'

TypeScript Best Practices

Type Definitions

/**
 * User profile information
 */
export interface User {
  /** Unique identifier */
  id: string
  /** User's email address */
  email: string
  /** Full name */
  full_name: string | null
  /** Avatar URL */
  avatar_url: string | null
  /** Account creation timestamp */
  created_at: string
}
 
/**
 * Input for creating a new user
 */
export interface CreateUserInput {
  email: string
  password: string
  full_name?: string
}

Function Documentation

/**
 * Creates a new organization with the specified parameters.
 *
 * @param data - Organization creation data
 * @param userId - ID of the user creating the organization
 * @returns Promise resolving to the created organization
 * @throws {ValidationError} If data is invalid
 * @throws {PermissionError} If user lacks permissions
 *
 * @example
 * ```typescript
 * const org = await createOrganization({
 *   name: 'Acme Corp',
 *   slug: 'acme-corp',
 *   tier: 'pro'
 * }, userId)
 * ```
 */
export async function createOrganization(
  data: CreateOrganizationInput,
  userId: string
): Promise<Organization> {
  // Validate input
  const validated = organizationSchema.parse(data)
 
  // Check permissions
  await checkPermission(userId, 'organizations.create')
 
  // Create organization
  const org = await db.from('organizations').insert(validated)
 
  return org
}

React Components

/**
 * Button component with variants and sizes.
 *
 * @component
 * @example
 * ```tsx
 * <Button variant="primary" size="lg" onClick={handleClick}>
 *   Click me
 * </Button>
 * ```
 */
interface ButtonProps {
  /** Button variant */
  variant?: 'primary' | 'secondary' | 'danger'
  /** Button size */
  size?: 'sm' | 'md' | 'lg'
  /** Click handler */
  onClick?: () => void
  /** Button content */
  children: React.ReactNode
  /** Disable button */
  disabled?: boolean
}
 
export function Button({
  variant = 'primary',
  size = 'md',
  onClick,
  children,
  disabled = false,
}: ButtonProps) {
  return (
    <button
      className={cn(styles.button, styles[variant], styles[size])}
      onClick={onClick}
      disabled={disabled}
    >
      {children}
    </button>
  )
}

Custom Hooks

/**
 * Hook to manage organization state and operations.
 *
 * @param organizationId - ID of the organization
 * @returns Organization state and operations
 *
 * @example
 * ```typescript
 * const { organization, loading, update } = useOrganization(orgId)
 *
 * // Update organization
 * await update({ name: 'New Name' })
 * ```
 */
export function useOrganization(organizationId: string) {
  const [organization, setOrganization] = useState<Organization | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<Error | null>(null)
 
  useEffect(() => {
    loadOrganization()
  }, [organizationId])
 
  async function loadOrganization() {
    try {
      setLoading(true)
      const data = await getOrganization(organizationId)
      setOrganization(data)
    } catch (err) {
      setError(err as Error)
    } finally {
      setLoading(false)
    }
  }
 
  async function update(data: Partial<Organization>) {
    const updated = await updateOrganization(organizationId, data)
    setOrganization(updated)
  }
 
  return { organization, loading, error, update }
}

Python Best Practices

Module Documentation

"""
Organization service module.
 
This module provides business logic for organization management,
including creation, updates, member management, and deletion.
 
Example:
    >>> from app.services.organizations import OrganizationService
    >>> org = await OrganizationService.create(
    ...     name="Acme Corp",
    ...     slug="acme-corp",
    ...     owner_id=user_id
    ... )
"""
 
from typing import List, Optional
from uuid import UUID

Class Documentation

class OrganizationService:
    """
    Service for managing organizations.
 
    This service handles all business logic related to organizations,
    including CRUD operations, member management, and billing integration.
 
    Attributes:
        db: Database connection instance
 
    Example:
        >>> service = OrganizationService()
        >>> org = await service.create(data, user_id)
    """
 
    def __init__(self, db=None):
        """Initialize organization service with optional database connection."""
        self.db = db or get_db()

Function Documentation

async def create_organization(
    name: str,
    slug: str,
    owner_id: UUID,
    tier: str = "free"
) -> Organization:
    """
    Create a new organization.
 
    Args:
        name: Organization name (1-100 characters)
        slug: URL-friendly identifier (lowercase, alphanumeric, hyphens)
        owner_id: UUID of the user creating the organization
        tier: Subscription tier, defaults to "free"
 
    Returns:
        Organization: The created organization object
 
    Raises:
        ValidationError: If input data is invalid
        ConflictError: If slug is already taken
        PermissionError: If user lacks permission
 
    Example:
        >>> org = await create_organization(
        ...     name="Acme Corp",
        ...     slug="acme-corp",
        ...     owner_id=uuid.uuid4(),
        ...     tier="pro"
        ... )
        >>> print(org.name)
        'Acme Corp'
    """
    # Validate input
    if not name or len(name) > 100:
        raise ValidationError("Name must be 1-100 characters")
 
    if not re.match(r'^[a-z0-9-]+$', slug):
        raise ValidationError("Invalid slug format")
 
    # Check if slug exists
    existing = await db.from_("organizations")\
        .select("id")\
        .eq("slug", slug)\
        .execute()
 
    if existing.data:
        raise ConflictError(f"Slug '{slug}' already exists")
 
    # Create organization
    result = await db.from_("organizations").insert({
        "name": name,
        "slug": slug,
        "tier": tier,
    }).execute()
 
    org = result.data[0]
 
    # Add owner as member
    await db.from_("organization_members").insert({
        "organization_id": org["id"],
        "user_id": owner_id,
        "role": "owner",
    }).execute()
 
    return Organization(**org)

Type Hints

from typing import List, Optional, Dict, Any, Union
from uuid import UUID
from datetime import datetime
 
class Organization:
    """Organization model."""
 
    id: UUID
    name: str
    slug: str
    tier: str
    created_at: datetime
    updated_at: datetime
 
    def to_dict(self) -> Dict[str, Any]:
        """Convert organization to dictionary."""
        return {
            "id": str(self.id),
            "name": self.name,
            "slug": self.slug,
            "tier": self.tier,
            "created_at": self.created_at.isoformat(),
            "updated_at": self.updated_at.isoformat(),
        }

Code Comments

When to Comment

Do comment:

  • Complex business logic
  • Non-obvious decisions
  • Workarounds
  • Security considerations
  • Performance optimizations
// Hash API key using SHA-256 for secure storage.
// We only store the hash to prevent key exposure if database is compromised.
const keyHash = crypto.createHash('sha256').update(apiKey).digest('hex')

Don't comment:

  • Obvious code
  • What the code does (code should be self-documenting)
// Bad: Comment states the obvious
// Increment counter by 1
count++
 
// Good: Self-documenting code
function incrementPageViewCount() {
  pageViews++
}

TODO Comments

Use TODO comments for future work:

// TODO(username): Add pagination support
// TODO: Implement caching for frequently accessed orgs
// FIXME: Handle race condition when multiple users join simultaneously
// HACK: Temporary workaround until API v2 is released

Naming Conventions

Variables

// Use descriptive names
const userEmail = 'user@example.com'  // Good
const e = 'user@example.com'          // Bad
 
// Boolean variables
const isLoading = true
const hasPermission = false
const canEdit = true
 
// Arrays/collections
const users = []
const organizationIds = []

Functions

// Verb + noun
function createOrganization() {}
function updateUserProfile() {}
function deleteApiKey() {}
 
// Boolean returns
function isAuthenticated() {}
function hasPermission() {}
function canAccessResource() {}

Constants

// Upper snake case
const MAX_FILE_SIZE = 5 * 1024 * 1024
const DEFAULT_PAGE_SIZE = 20
const API_BASE_URL = 'https://api.example.com'

Error Handling

Meaningful Errors

// Bad: Generic error
throw new Error('Failed')
 
// Good: Specific error with context
throw new ValidationError(
  'Organization name must be between 1 and 100 characters',
  { field: 'name', value: name }
)

Error Documentation

class OrganizationService:
    async def delete(self, org_id: UUID, user_id: UUID) -> None:
        """
        Delete an organization.
 
        Args:
            org_id: Organization ID to delete
            user_id: ID of user requesting deletion
 
        Raises:
            NotFoundError: Organization doesn't exist
            PermissionError: User lacks delete permission
            ConflictError: Organization has active subscription
 
        Note:
            This is a soft delete. The organization is marked as deleted
            but data is retained for 30 days before permanent deletion.
        """

Testing Organization

tests/
  unit/
    services/
      test_organizations.py
    utils/
      test_validation.py
  integration/
    api/
      test_organization_endpoints.py
  e2e/
    test_organization_workflow.spec.ts

Next Steps