Skip to content
Clean CodeChapter 8 / 57Beginner6 min read

Small Functions & Single Responsibility

Single responsibility principle functions par kaise lagta hai. Chhote functions, ek kaam, ek level of abstraction aur side effects ko alag rakhna.

On this page

1. Yeh practice kya hai?

Single Responsibility ka matlab: function ke badalne ki ek hi wajah ho. Agar email ka format badle aur discount ka hisaab bhi badle, aur dono ek hi function chhedein, to us function ki do zimmedariyan hain.

HissaMatlab
Ek kaamNaam ek verb, jumla mein "aur" nahi
Size40 lines max, 20 target
Ek level of abstractionHigh level steps aur low level details ek hi function mein mix na hon
Pure jahan mumkinData badalna ek function, database ya network doosra
Parameters3 se zyada related values ho to ek object

2. Kyun zaroori hai?

Lamba function ek kamra hai jis mein sab kuch bikhra hai. Ek cheez dhoondne ke liye poora kamra dekhna parta hai, aur kuch hilao to doosri cheez gir jati hai.

Ek bara functionChhote focused functions
150 lines, poora parhe bina kuch badalna khatarnak15 lines, ek nazar mein samajh
Test karne ke liye database aur email dono mockPure hisaab bina mock ke test
Bug kahan hai, poora function debug karoNaam se pata chalta hai kahan dekhna hai
Ek hissa reuse karna ho to copy pasteChhota function seedha import
Do log ek hi function mein alag cheez badlein, merge conflictAlag functions, alag changes

3. Kab follow karein?

LevelKitna zarooriKyun
Learning projectZaroori, line count se zyada "ek kaam" par focusFunction todna seekhna programming ki bunyad hai
Production code40 line limit review mein checkLamba function bugs ka ghar aur test ka dushman hai
Senior levelPehchano kab todna aur kab nahiZabardasti todne se bhi coupling paida hoti hai

4. Bura vs acha code

ts
export async function checkout(cartId: string, userId: string, couponCode?: string) {
  const cart = await db.cart.findUnique({ where: { id: cartId }, include: { items: true } });
  if (!cart) throw new Error("no cart");
  let total = 0;
  for (const item of cart.items) {
    total += item.price * item.quantity;
  }
  if (couponCode) {
    const coupon = await db.coupon.findUnique({ where: { code: couponCode } });
    if (coupon && coupon.expiresAt > new Date()) {
      total = total - total * coupon.percent / 100;
    }
  }
  const order = await db.order.create({ data: { userId, total, cartId } });
  const user = await db.user.findUnique({ where: { id: userId } });
  await mailer.send(user!.email, `Order ${order.id} confirmed, total ${total}`);
  return order;
}
ts
export async function checkout(input: CheckoutInput) {
  const cart = await carts.require(input.cartId);
  const coupon = await coupons.find(input.couponCode);
  const order = await orders.create(input.userId, cart, total(cart.items, coupon));

  await notify(order);

  return order;
}
ts
function subtotal(items: CartItem[]) {
  return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}

function total(items: CartItem[], coupon: Coupon | null) {
  if (!coupon || isCouponExpired(coupon)) {
    return subtotal(items);
  }

  return subtotal(items) * (1 - coupon.percent / 100);
}
Farq kya hai?BuraAcha
ZimmedariyanLoad, hisaab, coupon, save, email sab ek jagahcheckout sirf steps ki tarteeb
Abstractionfor loop aur business flow mixUpar flow, neeche details
TestingHisaab test karne ke liye database chahiyetotal pure hai, seedha test
Parameters3 positional, order yaad rakhoEk CheckoutInput object
Parhna20 dense linesHar function 10 se kam lines

checkout ab ek kahani ki tarah parhta hai: cart lo, coupon lo, order banao, batao.

5. Kaise apply karein?

Bare function ko todna
Function ko ek jumla mein describe karo
Har "aur" ek alag function ka nishan hai
Pure hisaab ko side effects se alag nikalo
Har nikle hisse ko kaam ke mutabiq naam do
Bahar wala function sirf steps call kare
Tests chalao, behaviour same hona chahiye

React component par bhi yahi lagta hai. Jo component data fetch kare, use transform kare aur render kare, woh teen kaam hai: hook fetch kare, pure function transform kare, component render kare.

6. Exceptions aur common mistakes

Line count rule ka nishana hai, khud rule nahi. Logic decide kare: 25 fields ki ek seedhi mapping ek hi idea hai aur poori reh sakti hai. Lekin 8 lines ka function jo do alag kaam kare, use do functions banna chahiye.

Ek mukammal domain flow ko zabardasti 10 tukron mein todna bhi galat hai. Agar har tukra sirf ek jagah se call ho aur doosre ke andar ki details jaane bina samajh na aaye, to aap ne coupling barhayi hai, ghatayi nahi.

Galati: Function ko sirf line count ke liye todna

Why? part1, part2 jaise tukre koi alag kaam nahi karte, parhne wala ab teen jagah jump karta hai.

Behtar: Tab todo jab hissa apna alag naam aur alag wajah-e-badlav rakhta ho.

Galati: Hisaab ke beech mein database ya network call

Why? Pure logic test karne ke liye ab mock chahiye, aur hisaab ki galti side effect se chhup jati hai.

Behtar: Pehle data lao, phir pure function se hisaab karo, phir result save karo.

Galati: Boolean parameter se do kaam

Why? send(order, true) dekh kar pata nahi chalta true kya karta hai, function do raaston wala ban jata hai.

Behtar: Do alag functions banao jin ke naam farq batayein.

Galati: Bohat saare positional parameters

Why? create(a, b, c, d, e) mein order galat hua to TypeScript bhi nahi pakar sakta agar types same hon.

Behtar: Related values ko ek typed object mein do.

7. Pehle aur baad mein kya seekhein?

Final quick revision

CheckSawal
Ek kaamKya function ek jumla mein bina "aur" ke describe hota hai?
SizeKya 40 se kam, behtar 20 se kam lines?
AbstractionKya flow aur details alag levels par hain?
PureKya hisaab side effects se alag hai?
ParametersKya 3 se zyada related values object mein hain?
ZabardastiKya koi tukra bina wajah ke bana?