JavaScript · Closures · Tech Lead · Architecture
When designing a library API, when would you prefer closure-based factories over class instances with prototype methods?
Short Interview Answer
Prefer closures for true privacy and simple captured config; prefer classes/prototypes for shared methods, instanceof, subclassing, and lower per-instance function cost.
Detailed Explanation
Closure factories excel when: you want hard privacy, a small surface area, and configuration captured once (`createClient(options)`). They compose well with functional style. Classes/prototypes excel when: you need shared methods on a prototype (memory), inheritance, `instanceof`, decorators, or framework integration that expects constructables. Mixed approach is common: class with private fields (`#`) for privacy plus shared methods. At lead level, decide based on allocation profiles, testability, serialization (`toJSON`), and whether consumers need to extend types. Document lifecycle: closures that register listeners must expose `dispose`.
Interview Tip
Give a decision matrix — interviewers hire for trade-off thinking.
Common Mistake
Declaring one style always superior without context (memory, extensibility, team conventions).