Refactoring Patterns
Refactoring Patterns
Section titled “Refactoring Patterns”Concrete patterns to break cycles. For the step-by-step process, see Fixing Cycles. For an overview, see Circular Dependencies.
Pattern 1: Extract Shared Module
Section titled “Pattern 1: Extract Shared Module”Before:
A.js → B.jsB.js → A.js (cycle!)Both A and B use shared utilities from each other.
After:
A.js → shared.jsB.js → shared.jsExtract common code to a new module.
Pattern 2: Dependency Injection
Section titled “Pattern 2: Dependency Injection”Before:
import { EmailService } from './email-service';
export class UserService { private emailService = new EmailService();}
// email-service.tsimport { UserService } from './user-service'; // Cycle!
export class EmailService { getUser() { return new UserService(); }}After:
import type { IEmailService } from './interfaces';
export class UserService { constructor(private emailService: IEmailService) {}}
// email-service.tsimport type { IUserService } from './interfaces';
export class EmailService { constructor(private userService: IUserService) {}}
// interfaces.ts (new, no dependencies)export interface IUserService { /* ... */ }export interface IEmailService { /* ... */ }Pattern 3: Move Types to Definitions File
Section titled “Pattern 3: Move Types to Definitions File”Before:
import { Address } from './address';export interface User { address: Address; }
// models/address.tsimport { User } from './user'; // Cycle!
export interface Address { user: User; }After:
// models/types.ts (new)export interface User { address: Address; }export interface Address { userId: string; }
// models/user.tsimport { User } from './types';
// models/address.tsimport { Address } from './types';Pattern 4: Introduce Abstraction Layer
Section titled “Pattern 4: Introduce Abstraction Layer”Before:
UI Layer → Business LogicBusiness Logic → UI Layer (cycle!)After:
UI Layer → Abstraction → Business LogicIntroduce an interface or event system to break the cycle.
Further Reading
Section titled “Further Reading”- Fixing Cycles - Step-by-step process and quick wins
- SCC Overview - Metric overview
- Breaking Cycles Guide - More strategies