Back to .md Directory

Code Quality Rules

Defines rules for eliminating code duplication, extracting constants, and enforcing consistent error handling and validation patterns.

May 2, 2026
0 downloads
2 views
ai rag
View source

What this file does

Defines rules for eliminating code duplication, extracting constants, and enforcing consistent error handling and validation patterns.

When to use it

  • Starting a new project and want to enforce code quality from day one
  • Onboarding a team that needs clear duplication and extraction guidelines
  • Reviewing a codebase with repeated logic and magic numbers
  • Setting up linting or review standards for a shared repository

Code Quality Rules

Focus: Prevent duplication, extract constants, create reusable utilities.


No Code Duplication

When you see repeated patterns (2+ places):

  1. Identify the duplication
  2. Extract to shared location:
    • utils/ for general utilities
    • helpers/ for domain-specific helpers
    • lib/ for larger reusable modules
    • DrawingUtils.cs for rendering utilities (this project)
  3. Import and reuse everywhere

Examples

❌ WRONG: Same API error handling in 10 files
✅ CORRECT: Single handleApiError() in utils/api.js

❌ WRONG: Duplicate validation logic across 5 files
✅ CORRECT: Extract to helpers/validation.js and import

❌ WRONG: Steering logic duplicated in Optical.cs and Flow.cs
✅ CORRECT: Extract to DrawingUtils.ApplySteeringBehavior()


Extract Complex Types/Structures Once

For complex data structures used in multiple places:

Create reusable types/interfaces/structs in one place:

  • types/ directory for TypeScript interfaces
  • models/ for data models/schemas
  • schemas/ for validation schemas
  • Shared utility files for structs (like DrawingUtils.cs)

Examples

❌ WRONG:

// Repeated in 5 files
const user = {
  id: string,
  email: string,
  profile: { name: string, avatar: string }
}

✅ CORRECT:

// types/user.ts
export interface User {
  id: string;
  email: string;
  profile: UserProfile;
}

// Import everywhere
import { User } from '@/types/user';

Configuration Over Hard-Coding

NEVER hard-code values that might change:

Extract to configuration:

  • Magic numbers → constants (at top of class or constants file)
  • Business logic thresholds → config object
  • Repeated strings → constants
  • Feature flags → environment variables

Examples

❌ WRONG:

if (userAge >= 18 && creditScore > 650) {
  // approve loan
}

✅ CORRECT:

// At top of class
private const int MIN_AGE = 18;
private const int MIN_CREDIT_SCORE = 650;

// In code
if (userAge >= MIN_AGE && creditScore > MIN_CREDIT_SCORE) {
  // approve loan
}

Minimal, Purposeful Comments

Only comment when necessary:

✅ DO comment:

  • Complex business logic that isn't obvious
  • Non-obvious performance optimizations
  • Workarounds for bugs/quirks
  • Important edge cases

❌ DON'T comment:

  • What the code obviously does
  • Every single line
  • Self-explanatory variable names
  • Simple loops or conditions

Examples

❌ WRONG:

// Get the user
const user = getUser(id);

// Check if user exists
if (user) {
  // Return the user name
  return user.name;
}

✅ CORRECT:

const user = getUser(id);

// Fallback to 'Guest' maintains backwards compatibility with legacy API consumers
return user?.name ?? 'Guest';

Code Quality Principles

  • Simple over clever - readable code beats smart code
  • Explicit over implicit - clear is better than concise
  • Functional over complex - pure functions when possible
  • Reuse over reinvent - don't rebuild what exists

Error Handling

Every operation that can fail should handle errors gracefully:

// For async operations
try {
  var data = await FetchData(id);
  return data;
} catch (Exception error) {
  Logger.Error($"Failed to fetch data: {error.Message}", new { id });
  throw new Exception($"Data fetch failed: {error.Message}");
}

// For functions that might receive bad input
if (string.IsNullOrEmpty(id)) {
  throw new ArgumentException("Valid string ID required");
}

Validation

Validate at boundaries (API endpoints, user input, external data):

public void ProcessUser(UserInput input) {
  // Validate early
  if (string.IsNullOrEmpty(input?.Email) || string.IsNullOrEmpty(input?.Name)) {
    throw new ValidationException("Email and name required");
  }
  
  // Then process
  CreateUser(input);
}

END OF QUALITY RULES

What's inside

7 sections covering duplication, type extraction, configuration, comments, principles, error handling, and validation with 6 code examples

Change this for your project

  • Replace DrawingUtils.cs with your own rendering utility class name
  • Replace utils/api.js with your actual API utility path
  • Replace helpers/validation.js with your validation helper path
  • Replace types/user.ts with your own type file path

Where it goes

Keep it in your repository where the agent or team that needs it will read it.

Worth borrowing

  • Grouping extraction targets by layer (utils, helpers, lib) rather than by file type
  • Using concrete before/after examples to teach a principle instead of just stating it

Related Documents