Why This Matters at Engineering Leadership Scale
Because AI generates boilerplate instantly, PR sizes across many teams have jumped 40% to 80% while real feature delivery stayed flat. Left unchecked, AI defaults to six files, an AbstractWebhookProcessor, a WebhookProcessorFactory, duplicate DTO mappers, and defensive try/catch blocks that silently return null on failure.
At leadership scale, abstraction bloat is a reliability risk, not a style preference. Bloated 600-line diffs exhaust reviewers so real IDOR or concurrency bugs slip through. Worse, AI's "defensive" catch blocks swallow database outages and return 200 OK, causing silent data loss that surfaces weeks later during customer escalations.
Core Mental Model & Framework
Apply the "2 AM Debug Test" to every abstraction in an AI-assisted PR: "If we are paged at 2 AM, does this abstraction make the failure clearer or harder to trace?"
| AI Bloat Pattern | Why AI Generates It | Production Cost | Exact Refactoring Action |
|---|---|---|---|
Single-impl interfaces & AbstractFactory (WebhookProcessorFactory for 1 provider) | Mirrors textbook Java/C# patterns | 4 extra files of indirection; reviewer fatigue | Delete factory & interface; write one direct function until a second real provider exists |
Pass-through DTO mappers (mapInput -> mapCommand -> mapEntity) | Prompt mentioned "clean architecture" | Duplicates fields across 3 layers; silent field drops | Validate once with Zod at the boundary and pass typed objects directly |
Swallowed errors in try/catch (catch (e) { console.error(e); return false; }) | AI tries to "prevent crashes" | Turns DB outages into 200 OK; breaks webhook retries & alerts | Delete speculative catch blocks inside helpers; propagate errors to central HTTP error middleware |
Local EventEmitter inside CRUD | Speculative decoupling | Breaks stack traces and linear flow | Call downstream steps sequentially with explicit await |
Step-by-Step Implementation Tutorial
1. Count Real Implementations Before Reading Line 1
Inspect the file tree first. If you see Abstract*, Base*, *Factory, or I*Handler backed by only one real implementation (not an explicit test seam like Clock), flag it for deletion immediately.
2. Audit the Bloated AI Diff vs. the Direct Refactored Handler
// =========================================================================
// BLOATED AI-GENERATED DIFF (DO NOT APPROVE)
// Single-implementation factory boilerplate + two swallowed-error bugs
// =========================================================================
export abstract class BaseWebhookProcessor<T> {
abstract canHandle(eventType: string): boolean;
abstract process(payload: T): Promise<boolean>;
}
class JiraPayloadMapper {
map(raw: any): JiraIssueEvent | null {
try {
return { eventId: raw.id, tenantId: raw.tenantId, key: raw.issue.key, status: raw.issue.fields.status.name };
} catch (err) {
// BUG 1: Swallows bad payload silently and masks 400 error
console.error("Mapping failed", err);
return null;
}
}
}
class JiraComplianceProcessor extends BaseWebhookProcessor<JiraIssueEvent> {
constructor(private readonly db: Pool) { super(); }
canHandle(eventType: string) { return eventType === "jira:issue_updated"; }
async process(evt: JiraIssueEvent): Promise<boolean> {
try {
await this.db.query(
`INSERT INTO compliance_events (tenant_id, event_id, issue_key, status)
VALUES ($1, $2, $3, $4) ON CONFLICT (tenant_id, event_id) DO NOTHING`,
[evt.tenantId, evt.eventId, evt.key, evt.status]
);
return true;
} catch (err) {
// BUG 2: Swallows Postgres outage! Handler returns 200 OK so Jira never retries!
console.error("DB insert failed", err);
return false;
}
}
}
class WebhookProcessorFactory {
private readonly list: BaseWebhookProcessor<any>[];
constructor(db: Pool) { this.list = [new JiraComplianceProcessor(db)]; }
get(type: string) { return this.list.find((p) => p.canHandle(type)) ?? null; }
}
export async function handleJiraWebhook(req: AuthenticatedRequest, res: Response, db: Pool) {
const proc = new WebhookProcessorFactory(db).get(req.body?.webhookEvent);
if (!proc) return res.status(200).json({ ignored: true });
const mapped = new JiraPayloadMapper().map(req.body);
if (!mapped) return res.status(200).json({ skipped: true });
await proc.process(mapped);
return res.status(200).json({ ok: true }); // Always 200 even when DB is down!
}Now look at the refactored diff: 55% fewer lines, zero speculative classes, strict Zod validation, and clean error propagation to central error middleware (500) so Jira automatically retries after a DB blip.
// =========================================================================
// FIXED REFACTORED DIFF
// Direct, readable, zero swallowed errors, 55% smaller diff, full coverage
// =========================================================================
import { z } from "zod";
const JiraIssueWebhookSchema = z.object({
id: z.string().min(1),
webhookEvent: z.string(),
issue: z.object({
key: z.string().min(1),
fields: z.object({ status: z.object({ name: z.string().min(1) }) }),
}),
});
export async function handleJiraWebhook(
req: AuthenticatedRequest, res: Response, next: NextFunction, db: Pool
) {
try {
if (req.body?.webhookEvent !== "jira:issue_updated") {
return res.status(200).json({ status: "ignored" });
}
const parsed = JiraIssueWebhookSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "Invalid webhook payload" });
const { id: eventId, issue } = parsed.data;
const tenantId = req.auth.tenantId; // Derived from verified webhook signature
// Let DB outages bubble to next(err) -> 500 so Jira retries safely
const result = await db.query(
`INSERT INTO compliance_events (tenant_id, event_id, issue_key, status)
VALUES ($1, $2, $3, $4)
ON CONFLICT (tenant_id, event_id) DO NOTHING RETURNING event_id`,
[tenantId, eventId, issue.key, issue.fields.status.name]
);
const status = result.rowCount === 0 ? "duplicate" : "recorded";
return res.status(200).json({ status, eventId });
} catch (err) {
return next(err); // Central error middleware logs structured error + returns 500
}
}3. Coach Your Tech Lead Without Micromanaging Every PR
When a Tech Lead approves two bloated 500-line AI PRs, pair for 15 minutes on one merged PR and ask: "If we debugged this at 2 AM, which abstractions actually earn their keep, and what happens if Postgres drops inside that catch?" Then let the Tech Lead codify a 2-line PR norm banning single-implementation factories and silent catch blocks.
Worked Production Scenario: Before vs. After
Context: A compliance squad engineer opened a 650-line AI-generated Jira webhook PR across 7 files (AbstractWebhookHandler, WebhookProcessorFactory, JiraEventMapper, wrapper services). Buried inside the bloat were a missing tenant_id check and a catch { return false; } that silently dropped 41 compliance events during a 10-second staging DB failover.
After: During a 15-minute audit, the team deleted 240 lines of unused factory/mapper boilerplate and removed the swallowing catch blocks, landing a direct 180-line handler with 5 real integration tests.
| Metric | Before | After |
|---|---|---|
| PR diff size & file count | 650 lines / 7 files | 180 lines / 2 files (-72%) |
| Dropped events during 10s DB failover | 41 lost (200 OK) | 0 lost (500 -> retried) |
| Reviewer audit time | 48 minutes (high fatigue) | 9 minutes (clear flow) |
| Bloated AI PRs approved next 2 sprints | 2 / sprint | 0 |
Common Failure Modes & Anti-Patterns
- Swallowing errors in helpers to "be safe": Returning
nullorfalseinsidecatchturns DB outages into silent data loss and suppresses alerts. Fix: Catch only to recover meaningfully, add domain context before re-throwing, or respond in central error middleware. - Building a "Plugin Factory" for hypothetical providers: Speculating on future GitHub/Linear webhooks before requirements exist almost always guesses the wrong interface. Fix: Apply the Rule of Three - write direct functions for provider #1 and extract a shared interface only once provider #2 or #3 reveals the true seam.
- Rewriting bloated PRs yourself as the manager: Fixes one branch fast but turns you into a permanent bottleneck. Fix: Leave concrete comments explaining the 2 AM debug and retry failure risks, and let the author refactor in 25 minutes.
How to Handle Pushback in the Room
Skeptical Senior Engineer: "Deleting WebhookProcessorFactory violates Open/Closed Principle - what if Product adds GitHub webhooks next quarter?"
Calm Response: "Adding a direct handleGitHubWebhook function behind /webhooks/github is already open for extension and takes ten minutes when funded. Paying a 240-line indirection tax today slows every review now and usually guesses the wrong abstraction anyway."
Busy Tech Lead: "Copilot wrote those classes in ten seconds and tests pass - why spend 25 minutes refactoring working code?"
Calm Response: "Code is generated in ten seconds and read fifty times over two years, including during 2 AM outages. Deleting dead wrappers and silent catch blocks cuts review fatigue in half and keeps real bugs from hiding inside boilerplate."
Key Takeaways & This Week's Action Rep
- Apply the 2 AM Debug Test: Delete single-implementation factories, interfaces, and identical pass-through mappers.
- Ban silent error swallowing: Never allow
catch (e) { console.error(e); return false/null; }in business helpers. - Shrink AI diffs to improve bug detection: Cutting 50% of boilerplate directly raises reviewer accuracy on security and race conditions.
- Coach Tech Leads via 15-minute pairing: Build a shared squad standard instead of taking over PRs yourself.
This Week's Action Rep: Pick one recently merged AI-assisted PR over 300 lines. Pair with your Tech Lead for 15 minutes to cut speculative abstractions and silent catch blocks, and add "No single-implementation factories; no silent catch blocks" to your PR norm.