{
  "$type": "site.standard.document",
  "canonicalUrl": "https://rednafi.com/shards/2026/03/ideal-dispatch-mechanism/",
  "description": "Switch, map of functions, and interface registry for dispatching in Go.",
  "path": "/shards/2026/03/ideal-dispatch-mechanism/",
  "publishedAt": "2026-03-31T00:00:00.000Z",
  "site": "at://did:plc:fgtm2c26vfcj74rfmeggbyqj/site.standard.publication/3mnl6f7ob462z",
  "tags": [
    "Go",
    "API"
  ],
  "textContent": "Someone [asked] in r/golang:\n\n> I'm creating a multi-format converter that converts all graphic formats used on a user's\n> system to JPG. I can use a switch based on the file extension to choose how to convert\n> each file. Is there a more idiomatic way to structure the code, or is a switch preferable\n> for this kind of problem? What construct would be more optimal to maintain, extend, and\n> use long term, based on your experience, in place of a switch (number of formats up to\n> 20)?\n\nI took a [stab] at it there. Here's the longer version.\n\n---\n\nA switch is fine as a starting point, and I'd start there. Once you hit 10-20 formats, it\nbecomes a long, central piece of code that you keep touching every time a new format shows\nup. But I still wouldn't change anything if maintaining a bunch of case arms isn't actually\ncausing problems.\n\nBut sometimes I don't start with a switch and instead go straight to a map of functions.\nThis removes the growing conditional. Adding a new format becomes a one-line map entry\ninstead of editing a big block:\n\nThis is usually where I stop. But you can keep going and replace the map of functions with a\nmap of interfaces. Instead of a flat function map, you define a converter interface and keep\na registry of types that satisfy it. The dispatch logic stays the same:\n\nNow instead of a map of functions, you keep a registry of converters:\n\nEach format can live in its own file and register itself. This avoids touching central code\nwhen adding new formats, which is the main long-term win:\n\nI rarely go for the interface approach unless I know for sure that the map of functions is a\nbottleneck, which almost never happens. It feels a bit heavy, and I'm not a big fan of the\nextra abstraction unless it actually solves a real problem.\n\n---\n\nIf you want to avoid global state in the map of func approach, wrap the map in a struct and\nhang Convert off of it:\n\n\n\n\n[asked]:\n    https://www.reddit.com/r/golang/comments/1s8j4qj/\n\n[stab]:\n    https://www.reddit.com/r/golang/comments/1s8j4qj/comment/odh77wi/",
  "title": "What's the ideal dispatch mechanism?"
}