Java
programming
switch statement
string matching
coding techniques

Switch statement for matching substrings of a String

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Traditional switch statements in many languages match exact values, not substrings. Developers trying to route logic based on partial text often force awkward switch patterns that are hard to maintain. A better design uses if/else chains, pattern matching, lookup tables, or regex-based dispatch depending on complexity. The goal is to keep matching rules explicit, deterministic, and testable.

Core Sections

1. Why normal switch is insufficient

Example in JavaScript:

javascript
1const input = "user:create";
2
3switch (input) {
4  case "create":
5    // not matched
6    break;
7}

switch compares whole value equality, so substring intent is not met.

2. Use if with includes for simple cases

javascript
1if (input.includes("create")) {
2  handleCreate();
3} else if (input.includes("delete")) {
4  handleDelete();
5}

This is clear for short rule sets.

3. Regex-based routing for structured patterns

javascript
1const rules = [
2  { re: /^user:create$/, fn: handleCreate },
3  { re: /^user:delete$/, fn: handleDelete },
4  { re: /^order:/, fn: handleOrder },
5];
6
7for (const r of rules) {
8  if (r.re.test(input)) {
9    r.fn();
10    break;
11  }
12}

Regex gives control over anchors and prefixes.

4. Map-based dispatch with normalized keys

If strings have predictable tokens, split first and dispatch by token.

javascript
1const [entity, action] = input.split(":");
2const handlers = {
3  "user:create": handleCreate,
4  "user:delete": handleDelete,
5};
6(handlers[`${entity}:${action}`] ?? handleDefault)();

This keeps behavior deterministic and fast.

5. Language-specific pattern matching

Some languages provide advanced pattern matching (for example C# switch expressions with guards). Use guarded cases for readability when available.

6. Testing and precedence

When multiple substrings may match, define precedence explicitly and add tests to prevent accidental rule-order regressions.

Validation and production readiness

A working snippet is only the first step. To make the solution dependable, validate behavior under representative inputs and operating conditions. Build a small test matrix that includes normal cases, boundary values, and malformed data so failure modes are explicit. If the topic involves time, concurrency, or networking, add at least one test that simulates delayed execution and one test that verifies timeout handling. This catches race conditions and environment-specific bugs that rarely appear in local happy-path runs.

Operational clarity matters as much as correctness. Document assumptions near the implementation: runtime version, required dependencies, expected timezone or locale rules, and platform limitations. Ambiguous assumptions are a major source of production incidents because teammates run the same logic under different defaults. Use structured logs around critical branches and external calls so debugging does not require ad hoc reproduction. Logs should include identifiers and concise context, but avoid sensitive payloads.

For recurring jobs or frequently executed code paths, add observability and guardrails. Define simple success metrics, retry boundaries, and explicit rollback or fallback behavior. Silent retries with no upper limit can hide systemic failures and increase downstream impact. Keep a lightweight pre-deploy checklist in source control so changes remain auditable and repeatable across environments.

text
1release_checklist:
2  - tests cover edge cases and failure paths
3  - runtime and dependency versions documented
4  - logs/metrics confirm expected execution path
5  - retries and timeouts are bounded
6  - rollback or fallback plan is defined

Teams that treat these checks as part of the default implementation workflow usually spend less time on incident triage and more time shipping stable improvements.

Common Pitfalls

  • Expecting exact-value switch to perform substring matching.
  • Using broad substring checks that match unintended inputs.
  • Omitting rule-precedence documentation in multi-pattern routing.
  • Mixing regex and raw string checks inconsistently.
  • Skipping tests for overlapping pattern scenarios.

Summary

Switch statements are usually wrong for substring matching unless language features add explicit pattern guards. Prefer clear alternatives: includes for simple rules, regex for structured matching, or map dispatch for exact tokenized routes. Explicit precedence and tests make string-routing logic maintainable over time.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.