Control Flow
Maps Over Switch
Prefer using maps with function values over switch statements when dispatching based on string or integer keys. This approach is more maintainable, extensible, and testable.
Prefer
1type handlerFunc func (input Request) (Response, error)
2
3var handlers = map[string]handlerFunc{
4 "create": handleCreate,
5 "update": handleUpdate,
6 "delete": handleDelete,
7}
8
9func dispatch(action string, req Request) (Response, error) {
10 handler, exists := handlers[action]
11 if !exists {
12 return Response{}, fmt.Errorf("unknown action: %s", action)
13 }
14 return handler(req)
15}
Avoid
1func dispatch(action string, req Request) (Response, error) {
2 switch action {
3 case "create":
4 return handleCreate(req)
5 case "update":
6 return handleUpdate(req)
7 case "delete":
8 return handleDelete(req)
9 default:
10 return Response{}, fmt.Errorf("unknown action: %s", action)
11 }
12}
Exceptions
- Type switches (
switch v := value.(type)) are appropriate for type assertions. - Switch statements are acceptable when matching on complex conditions or ranges.
- Small, simple switches (2-3 cases) where a map would add unnecessary complexity.