Skip to content
Preptima
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

Related Topics