programming
optimization
coding
Python
algorithms

Better optimization technique using if/else or dictionary

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Choosing between long if/else chains and dictionary-based dispatch depends on problem shape. For fixed command-to-action routing, dictionary dispatch improves readability and extensibility. For complex conditional logic with ranges or multi-field predicates, structured branching or strategy objects are often clearer.

Short troubleshooting answers often solve the immediate error but miss maintainability concerns such as reproducibility, observability, and rollback safety. A complete implementation should make assumptions explicit, validate edge cases, and produce diagnostics that are useful during incidents.

When adapting snippets, verify version compatibility, runtime environment, and operational limits before rollout. Small contextual differences, such as framework version, deployment topology, or data shape, can change behavior significantly.

Core Sections

1. Establish a minimal correct solution

For discrete command lookup, dictionary dispatch is concise and reduces repetitive comparisons. It also makes adding new commands a one-line change.

python
1def handle_start():
2    return 'started'
3
4def handle_stop():
5    return 'stopped'
6
7handlers = {
8    'start': handle_start,
9    'stop': handle_stop,
10}
11
12cmd = 'start'
13result = handlers.get(cmd, lambda: 'unknown')()
14print(result)

This baseline should stay intentionally simple so correctness is easy to verify. Once the minimal behavior is confirmed, extend it with error handling and performance considerations rather than starting with complex abstractions.

2. Harden for production requirements

When conditions involve complex business rules, separate rule evaluation from action execution. This avoids giant boolean expressions and makes testing each rule easier.

python
1from dataclasses import dataclass
2
3@dataclass
4class Order:
5    total: float
6    vip: bool
7
8
9def choose_discount(order: Order) -> float:
10    if order.vip and order.total > 100:
11        return 0.20
12    if order.total > 200:
13        return 0.15
14    return 0.05

Production hardening usually includes explicit validation, clear failure semantics, and safe resource lifecycle management. It also helps to centralize configuration and shared logic so behavior remains consistent across environments and teams.

3. Validate and operate with confidence

Optimization should be evidence-driven. Branching style rarely dominates runtime unless executed at very high frequency. Prioritize clarity first, then profile hotspots and optimize only where measurable gains justify added complexity.

Add a practical verification loop with one happy-path test, one edge-case test, and one failure-path test. Pair tests with lightweight runtime signals such as error rates, latency percentiles, or startup checks so regressions are detected early.

Operational readiness includes rollback planning. Even correct code may fail under unexpected dependencies or data. Documenting rollback steps and fallback behavior reduces recovery time and deployment risk.

Implementation depth also includes long-term operability. Define clear ownership of configuration, data contracts, and failure handling so support engineers can diagnose issues without reverse engineering intent from old commits. Where possible, capture representative input and output examples in tests, because executable examples age better than prose-only documentation.

For production systems, add lightweight observability close to the critical path: structured logs for key decisions, counters for failure categories, and latency metrics around expensive operations. These signals should map to user impact directly so on-call responders can prioritize correctly under pressure. Strong observability turns debugging from guesswork into a bounded investigation.

Finally, prepare rollback and fallback behavior before deploying significant changes. Even technically correct updates can fail due to environment differences, data anomalies, or dependency upgrades. A preplanned rollback path, feature flag, or degraded-mode strategy reduces mean time to recovery and allows teams to iterate quickly without risking prolonged outages.

Common Pitfalls

  • Replacing clear logic with clever dispatch tables that hide domain rules.
  • Using dictionary dispatch when rules depend on ranges, not exact keys.
  • Prematurely optimizing branch style without performance measurements.
  • Storing mutable global state in handlers and creating hidden side effects.
  • Forgetting default cases and causing runtime key errors.

Summary

Use dictionary dispatch for direct key-to-action mapping and structured conditionals for rule-heavy logic. Optimize based on profiling, not assumptions about if/else overhead. Pair implementation detail with testing and operational safeguards so the solution remains reliable as code, dependencies, and infrastructure evolve.


Course illustration
Course illustration

All Rights Reserved.