Code Quality Rules
Defines rules for eliminating code duplication, extracting constants, and enforcing consistent error handling and validation patterns.
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):
- Identify the duplication
- Extract to shared location:
utils/for general utilitieshelpers/for domain-specific helperslib/for larger reusable modulesDrawingUtils.csfor rendering utilities (this project)
- 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 interfacesmodels/for data models/schemasschemas/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.cswith your own rendering utility class name - Replace
utils/api.jswith your actual API utility path - Replace
helpers/validation.jswith your validation helper path - Replace
types/user.tswith 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
dbt Core
Defines a complete dbt project setup with layered architecture, SQL style, Jinja best practices, and CI/CD workflow guidance.
HarmonyOS 主题与样式 - Cursor Rules
Defines HarmonyOS theming rules for dark/light mode, page brightness, and screen-on control with code examples.
Cursor Development Environment
Documents a Docker-based dev container setup with test commands and OpenClaw agent configuration for the ClawDrive project.
Journey from Concept to Code: Transforming Cursor into a Devin-like AI Assistant
Documents the creation of aicode.cursorrules, a set of rules that turns Cursor/Windsurf into a Devin-like AI assistant with automated planning and self-evolution.