mediumDesignCodingMidSeniorStaff
Messages arrive with a type field and each type needs a different object built to process it. How do you design the creation so you do not end up with a growing switch statement?
6 min readUpdated 2026-08-15Target archetype: Big Tech, Enterprise Captive, Product Startup
Answer
Short answer
Replace the switch with a registry the application builds once at startup: a map from discriminator to a factory, validated for duplicate and missing keys as it is constructed, injected rather than global, and with a decided answer for a type the consumer has never seen.
Was this answer helpful?
Likely follow-ups
- A producer deploys a new type before the consumer knows about it. What should the consumer do with that message?
- When would an abstract factory be the better shape here rather than a flat registry?
- Your implementations register themselves in static initialisers and one of them never registers. Why?
- After a merge, two implementations claim the same type. Where does that fail, and at what moment?
Related questions
- Go gives you no project layout and no dependency-injection container. How do you structure a service so it stays testable as it grows?mediumAlso on dependency-injection5 min
- Angular, Vue and React are answers to the same problems. Compare how each handles change detection, reactivity and dependency injection.hardAlso on dependency-injection6 min
- You kick off background work from a controller action and it throws once the response has gone out. What is happening?mediumAlso on dependency-injection5 min
- When is a factory the right answer, when is a builder, and when should you just call the constructor?mediumAlso on factory7 min