Skip to content
Clean CodeChapter 11 / 57Intermediate6 min read

Fail Fast, No Defensive Fallbacks

Fail fast defensive programming ka farq. Missing data ko ?? [] se chhupane ki bajaye saaf error kyun do, aur ?? kab theek hai. TypeScript examples.

On this page

1. Yeh practice kya hai?

"Defensive" code har jagah default laga kar crash rokta hai. Sunne mein achha hai, lekin crash rokna aur bug rokna alag cheezein hain. Fail fast ka matlab: galti ko jaldi aur zor se saamne lao, jahan woh hui.

SituationSahi tareeqa
Value waqai optional hai (user ka nickname, config ka option)value ?? default bilkul theek
Value honi chahiye (database row, required field)if (!value) aur throw
Do valid raaste hainSaaf if / else, dono jaan boojh kar

2. Kyun zaroori hai?

Fallback crash ko rokta hai, bug ko nahi. Bug chhup kar aage chalta hai aur kahin aur, kisi aur shakal mein nikalta hai, jahan us ki wajah dhoondna bohat mushkil hai.

Defensive fallbackFail fast
order.items ?? [], order khaali dikha, customer ne paise de diye theError: order 42 has no items, foran pata chala
Dashboard 0 revenue dikhata hai, sab sochte hain sales nahi huiAPI ka bug pehle din pakra gaya
Bug hafton baad support ticket se pata chalta haiBug development ya pehle deploy par pata chalta hai
Galat data database mein save ho jata haiKaam ruk jata hai, ganda data nahi banta
Error kahin aur, wajah kahin aurError wahi jahan masla hai

3. Kab follow karein?

LevelKitna zarooriKyun
Learning projectSamjho ke ?? kab chhupata haiBeginner har error ko ?? se "fix" karta hai, yeh aadat jaldi todo
Production codeBohat zarooriChhupe hue bugs ganda data aur galat paise banate hain
Senior levelProducer tak trace karoSenior symptom nahi, wajah theek karwata hai

4. Bura vs acha code

ts
async function invoiceTotal(invoiceId: string) {
  const invoice = await db.invoice.findUnique({ where: { id: invoiceId } });
  const lines = invoice?.lines ?? [];
  const rate = invoice?.customer?.taxRate ?? 0;

  try {
    return lines.reduce((sum, line) => sum + line.amount, 0) * (1 + rate);
  } catch {
    return 0;
  }
}
ts
async function invoiceTotal(invoiceId: string) {
  const invoice = await db.invoice.findUnique({
    where: { id: invoiceId },
    include: { lines: true, customer: true },
  });

  if (!invoice) {
    throw new NotFoundError(`Invoice ${invoiceId} not found`);
  }

  return subtotal(invoice.lines) * (1 + invoice.customer.taxRate);
}
Farq kya hai?BuraAcha
Invoice na mileTotal 0, koi nahi jaanta kyunSaaf NotFoundError
Tax rate missingChupke se 0, galat billSchema mein required, missing ho hi nahi sakta
Khaali catchHar error nigal liyaError upar jata hai, log hota hai
Debugging"Total 0 kyun hai?" ghantonError message mein id aur wajah

?? throw kyun nahi

Kuch log helper bana kar ek line mein throw karte hain:

ts
const user = (await users.find(id)) ?? fail("User missing");

Strict house style is ki jagah saaf check maangta hai, taake har throw ek nazar mein dikhe aur guard pattern har jagah ek jaisa ho:

ts
const user = await users.find(id);

if (!user) {
  throw new NotFoundError(`User ${id} not found`);
}

Error ko context ke saath aage bhejo

ts
try {
  await payments.charge(order);
} catch (error) {
  throw new Error(`Charging order ${order.id} failed`, { cause: error });
}

cause asli error ko saath rakhta hai, aur message batata hai kis kaam mein fail hua.

5. Kaise apply karein?

Fallback likhne se pehle
Kya yeh value contract ke mutabiq optional hai?
Haan: ?? default theek hai
Nahi: missing hona bug hai
Guard lagao aur saaf message ke saath throw karo
Pata karo value kahan banti hai
Bug wahan theek karo, symptom par patch nahi

Frontend par aksar backend ki galti ?? [] se chhupai jati hai. Asli fix backend mein hai: woh field hamesha bheje, ya contract mein optional ho aur UI saaf "empty state" dikhaye.

6. Exceptions aur common mistakes

User ke saamne poori app crash nahi honi chahiye. Fail fast ka matlab white screen nahi. Error ko ek boundary par pakro (React error boundary, API ka error handler), log karo, aur user ko saaf message do. Bas beech mein chupke se nigal kar fake value mat banao.

Network jaisi cheezon par retry aur graceful fallback (cached data dikhana) ek soocha samjha design hai, chhupa hua bug nahi. Farq yeh hai ke woh jaan boojh kar aur log ke saath hota hai.

Galati: Required data par ?? [] ya ?? {}

Why? Bug crash ki jagah galat UI ya galat hisaab ban jata hai aur der se pakra jata hai.

Behtar: Guard aur throw karo, phir producer mein bug theek karo.

Galati: Khaali catch block

Why? Har error, network se le kar typo tak, chupke se gayab ho jata hai.

Behtar: Error ko context ke saath log karo ya cause ke saath dobara throw karo.

Galati: Optional chaining ki zanjeer har jagah

Why? a?.b?.c?.d batata hai ke aapko data ki shape ka pata nahi, aur undefined chupke se aage chala jata hai.

Behtar: Boundary par data parse karo, uske baad types par bharosa karo.

Galati: Error message mein koi context nahi

Why? Something went wrong se pata nahi chalta kaunsa record, kaunsa user, kaunsa kaam.

Behtar: Message mein id aur kaam ka naam likho, aur cause attach karo.

7. Pehle aur baad mein kya seekhein?

Final quick revision

CheckSawal
Optional?Kya ?? sirf waqai optional value par hai?
RequiredKya required value missing hone par throw hota hai?
CatchKya koi khaali catch hai?
ContextKya error message mein id aur kaam hai?
Root causeKya bug producer par theek hua?
BoundaryKya user ko crash ki jagah saaf message milta hai?