Rules Hub
Coding Rules Library
Encapsulate third-party integration logic in standalone functions
Avoid inline interaction with third-party globals (like analytics) inside components; extract them into named service functions.
Bad example
| 1 | useEffect(() => { |
| 2 | // Bad: Inline logic couples component to specific vendor implementation |
| 3 | if (window.analyticsVendor) { |
| 4 | const metadata = window.globalConfig?.metadata; |
| 5 | const payload = { |
| 6 | path: window.location.pathname, |
| 7 | category: metadata?.category || 'uncategorized', |
| 8 | referrer: document.referrer, |
| 9 | }; |
| 10 | |
| 11 | window.analyticsVendor.track('pageview', payload); |
| 12 | } |
| 13 | }, []); |
Explanation (EN)
The component directly accesses global window objects and constructs complex payloads inline. This makes the code hard to read, impossible to reuse, and tightly coupled to the specific analytics vendor.
Objašnjenje (HR)
Komponenta izravno pristupa globalnim window objektima i gradi složene podatke unutar same funkcije. To čini kod teškim za čitanje, nemogućim za ponovnu upotrebu i čvrsto vezanim za specifičnog pružatelja analitike.
Good example
| 1 | // services/analytics.ts |
| 2 | export function trackPageView(path: string, metadata?: Metadata) { |
| 3 | if (!window.analyticsVendor) return; |
| 4 |
|
| 5 | window.analyticsVendor.track('pageview', { |
| 6 | path, |
| 7 | category: metadata?.category || 'uncategorized', |
| 8 | referrer: document.referrer, |
| 9 | }); |
| 10 | } |
| 11 |
|
| 12 | // Component.tsx |
| 13 | useEffect(() => { |
| 14 | // Good: Logic is abstract, readable, and reusable |
| 15 | trackPageView(window.location.pathname, window.globalConfig?.metadata); |
| 16 | }, []); |
Explanation (EN)
The tracking logic is extracted into a standalone function. The component simply calls this function, focusing on *when* to track rather than *how*. This allows for easier testing and swapping of vendors.
Objašnjenje (HR)
Logika praćenja izdvojena je u zasebnu funkciju. Komponenta samo poziva tu funkciju, fokusirajući se na to *kada* pratiti, a ne *kako*. To omogućuje lakše testiranje i zamjenu pružatelja usluga.