Chain of Responsibility: गंदे बिज़नेस लॉजिक के लिए क्लीन कोड

Chain of Responsibility: गंदे बिज़नेस लॉजिक के लिए क्लीन कोड

Chain of Responsibility: गंदे बिज़नेस लॉजिक के लिए क्लीन कोड

चलो उस फंक्शन की बात करते हैं जो मेरे सपनों में आता था।

हर सिस्टम में एक टाइम ऐसा आता है जब एक फंक्शन बन जाता है जिसे कोई टच नहीं करना चाहता। शुरू होता है छोटा सा: एक सिंपल वैलिडेशन चेक, यहाँ एक if स्टेटमेंट, वहाँ एक और। फिर requirements आते जाते हैं, stakeholders बोलते हैं "बस एक छोटा सा exception चाहिए," और अचानक आप सामने होते हैं एक 500-लाइन के राक्षस के जो लगता है committee ने लिखा है (क्योंकि वही लिखा होता है)।

यहीं Chain of Responsibility pattern काम आता है—जादू से नहीं, discipline से। चलो देखते हैं कैसे ये classic design pattern आपके सबसे उलझे हुए बिज़नेस लॉजिक को सुलझा सकता है।

Chain of Responsibility है क्या?

इसके core में, Chain of Responsibility का मतलब है एक request को handlers की chain के along pass करना जब तक कोई उसे handle न कर ले। सोचो जैसे customer service escalation queue—हर इंसान आपकी प्रॉब्लम सॉल्व करने की कोशिश करता है, और अगर नहीं कर पाता तो अगले को pass कर देता है।

कोड के terms में, एक massive method रखने के बजाय जो हर possible scenario handle करे, आप बनाते हैं smaller, focused handlers की series। हर handler या तो request process करता है या अगले handler को pass कर देता है chain में।

Real-World Scenarios जहाँ CoR चमकता है

E-commerce Order Processing

सोचो: आप बना रहे हैं एक e-commerce platform, और आपका `processOrder()` function चाहिए discount codes, loyalty points, seasonal promotions, corporate accounts, VIP status, और special partnerships handle करे। आपका फंक्शन फूल जाता है hundreds of lines में nested conditionals के साथ।

Chain of Responsibility के साथ, आप बनाते हैं individual processors:

```javascript
class DiscountCodeHandler {
handle(order) {
// Apply discount logic
return next ? next.handle(order) : order;
}
}

class LoyaltyPointsHandler {
handle(order) {
// Apply loyalty points
return next ? next.handle(order) : order;
}
}
```

हर handler focus करता है एक चीज़ पर, जिससे testing और maintenance बन जाता है breeze।

Content Moderation Pipeline

Social media platforms face करते हैं complex moderation workflows। एक post को check करना पड़ता है community guidelines के against, scan करना hate speech के लिए, flag करना political content के लिए, review करना copyright violations के लिए, और assess करना misinformation के लिए—सब publication से पहले।

एक moderation function में सब ठूँसने के बजाय, आप बनाते हैं एक pipeline:

1. **Spam Detection Handler** – Obvious spam filter करता है
2. **Hate Speech Handler** – Abusive language flag करता है
3. **Copyright Handler** – Known copyrighted material के against check करता है
4. **Political Content Handler** – Sensitive political posts route करता है
5. **Final Review Handler** – Human moderator review

हर step या तो content appropriately handle करता है या पास कर देता है line में नीचे।

Payment Authorization Flow

Payment processing में होते हैं multiple layers validation और approval के। एक monolithic payment processor के बजाय, सोचो इस chain को:

1. **Fraud Detection Handler** – Suspicious transactions block करता है
2. **Credit Limit Handler** – Sufficient funds ensure करता है
3. **Bank Verification Handler** – Account validity confirm करता है
4. **Currency Conversion Handler** – International payments handle करता है
5. **Payment Gateway Handler** – Actual transaction process करता है

ये approach आसान बना देता है new verification steps add करना बिना existing code touch किये।

अपनी पहली Chain implement करना

यहाँ है एक practical implementation JavaScript में:

```javascript
// Base handler class
class BaseHandler {
constructor() {
this.nextHandler = null;
}

setNext(handler) {
this.nextHandler = handler;
return handler;
}

handle(request) {
if (this.nextHandler) {
return this.nextHandler.handle(request);
}
return null; // कोई handler request process नहीं कर पाया
}
}

// Concrete handlers
class AuthenticationHandler extends BaseHandler {
handle(request) {
if (!request.user) {
return { error: 'Authentication required' };
}
console.log('Authentication passed');
return super.handle(request);
}
}

class AuthorizationHandler extends BaseHandler {
handle(request) {
if (request.user.role !== 'admin') {
return { error: 'Insufficient permissions' };
}
console.log('Authorization passed');
return super.handle(request);
}
}

class ValidationHandler extends BaseHandler {
handle(request) {
if (!request.data || Object.keys(request.data).length === 0) {
return { error: 'Invalid data' };
}
console.log('Validation passed');
return super.handle(request);
}
}

// Usage
const authHandler = new AuthenticationHandler();
const authzHandler = new AuthorizationHandler();
const validationHandler = new ValidationHandler();

authHandler.setNext(authzHandler).setNext(validationHandler);

const result = authHandler.handle({
user: { role: 'admin' },
data: { amount: 100 }
});
```

Benefits जो actually matter करते हैं

**Maintainability**: हर handler एक चीज़ करता है अच्छे से। जब business rules बदलते हैं, आप सिर्फ relevant handler modify करते हैं।

**Testability**: Unit testing बन जाता है straightforward—आप test करते हैं each handler को isolation में बजाय complex scenarios mock करने के।

**Flexibility**: Processing steps reorder करने हैं? बस chain configuration बदल दो। Conditional routing चाहिए? Custom logic implement करो अपने handlers में।

**Debugging**: जब कुछ गड़बड़ होता है, आपको exactly पता होता है कौन सा handler fail हुआ क्योंकि हर एक log करता है अपना decision।

Common Pitfalls जिनसे बचना है

Handlers को 너무 generic या too specific बनाने के चक्कर में मत पड़ो। Balance ढूंढो जहाँ हर handler represent करे एक meaningful business rule। और handlers को aware मत बनाओ उनकी position in the chain के—उन्हें focus करने दो अपनी responsibility पर और chain पर trust करो।

याद रखो: Chain of Responsibility आपके सारे conditional logic replace करने के बारे में नहीं है। ये organize करने के बारे में है complex workflows जहाँ multiple distinct processing steps need to occur in sequence।

Tools और Frameworks जो CoR को अपनाते हैं

कई modern frameworks already implement करते हैं variations इस pattern के:

- **Express.js middleware** ([expressjs.com](https://expressjs.com)) uses करता है chain-like approach
- **ASP.NET Core middleware pipeline** follow करता है similar principles
- **Java Servlet Filters** implement करते हैं chain processing

भले ही आपका framework explicitly CoR use न करे, ये pattern समझने से आप design कर पाते हैं better middleware और interceptor architectures।

Chain of Responsibility कब NOT use करना

CoR कोई silver bullet नहीं है। Avoid करो जब:

- Processing steps tightly coupled हों और always together execute हों
- Performance critical हो और आपको minimize करना हो method call overhead
- Processing का order matter न करता हो या fixed हो
- आपके पास तीन से कम distinct processing steps हों

अपने codebase में इसे काम करवाना

Ready हो Chain of Responsibility introduce करने के लिए अपने project में? छोटे से शुरू करो:

1. Identify करो एक complex function जिसे सब avoid करते हैं touch करने से
2. Break करो उसे logical processing steps में
3. Create करो separate handler classes हर step के लिए
4. Wire करो उन्हें together एक chain में
5. Test करो thoroughly לפני expand करने के दूसरे areas में

Investment quickly pay off करता है reduced debugging time और cleaner code reviews में।

FAQ

**Q: Chain में errors कैसे handle करूँ?**
A: हर handler को या तो request successfully process करनी चाहिए या throw करना चाहिए appropriate exception। Consider करो एक error handler implement करने को chain के end में unprocessed requests catch करने के लिए।

**Q: क्या handlers request modify कर सकते हैं as it passes through?**
A: बिल्कुल! ये common practice है। हर handler enrich, validate, या transform कर सकता है request data subsequent handlers के लिए।

**Q: Asynchronous processing का क्या?**
A: Modern implementations अक्सर support करते हैं async/await patterns। बस ensure करो हर handler properly await करता है next handler को chain में।

**Q: ये Strategy pattern से कैसे compare करता है?**
A: Strategy choose करता है one algorithm many में से, जबकि Chain of Responsibility try करता है multiple handlers in sequence जब तक एक request handle न कर ले।

Chain of Responsibility की beauty इसकी simplicity में है। ये हर architectural problem solve नहीं करता, लेकिन जब correctly apply किया जाता है, ये transform कर देता है unmaintainable spaghetti code को organized, readable logic में जिसे आपका future self thank करेगा।

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment