General Clean Code Principles
Critical Rules
G5: DRY (Don't Repeat Yourself)
Every piece of knowledge has one authoritative representation.
typescript
// Bad - duplication
const taxRate = 0.0825;
const caTotal = subtotal * 1.0825;
const nyTotal = subtotal * 1.07;
// Good - single source of truth
const TAX_RATES: Record<string, number> = { CA: 0.0825, NY: 0.07 };
const calculateTotal = (subtotal: number, state: string): number => {
return subtotal * (1 + TAX_RATES[state]);
};
G16: No Obscured Intent
Don't be clever. Be clear.
typescript
// Bad - what does this do? return ((x & 0x0f) << 4) | (y & 0x0f); // Good - obvious intent return packCoordinates(x, y);
G23: Prefer Polymorphism to If/Else
typescript
// Bad - will grow forever
function calculatePay(employee: Employee): number {
if (employee.type === "SALARIED") {
return employee.salary;
} else if (employee.type === "HOURLY") {
return employee.hours * employee.rate;
} else if (employee.type === "COMMISSIONED") {
return employee.base + employee.commission;
}
throw new Error("Unknown employee type");
}
// Good - open/closed principle
interface Employee {
calculatePay(): number;
}
class SalariedEmployee implements Employee {
constructor(private salary: number) {}
calculatePay(): number { return this.salary; }
}
class HourlyEmployee implements Employee {
constructor(private hours: number, private rate: number) {}
calculatePay(): number { return this.hours * this.rate; }
}
class CommissionedEmployee implements Employee {
constructor(private base: number, private commission: number) {}
calculatePay(): number { return this.base + this.commission; }
}
G25: Replace Magic Numbers with Named Constants
typescript
// Bad
if (elapsedTime > 86400) {
// ...
}
// Good
const SECONDS_PER_DAY: number = 86400;
if (elapsedTime > SECONDS_PER_DAY) {
// ...
}
G30: Functions Should Do One Thing
If you can extract another function, your function does more than one thing.
G36: Law of Demeter (Avoid Train Wrecks)
typescript
// Bad - reaching through multiple objects const outputDir = context.options.scratchDir.absolutePath; // Good - one dot const outputDir: string = context.getScratchDir();
Enforcement Checklist
When reviewing AI-generated code, verify:
- • No duplication (G5)
- • Clear intent, no magic numbers (G16, G25)
- • Polymorphism over conditionals (G23)
- • Functions do one thing (G30)
- • No Law of Demeter violations (G36)
- • Boundary conditions handled (G3)
- • Dead code removed (G9)