Commit 8575c62
committed
feat(Test): add demo mapping HTTP codes to descriptions with switch expression
What
- Added Test class with main method printing:
- "Hello World"
- Description of HTTP status code 404 via getHTTPCodeDescWithSwitch().
- Implemented getHTTPCodeDescWithSwitch(int code) using modern switch expression.
- Cases:
- Exact matches: 100, 200, 301, 302, 400, 500, 502.
- Ranges via pattern + when clauses (preview feature / requires Java 21+):
- 100–199 → "Informational"
- 200–299 → "Successful"
- 303–399 → "Redirection"
- 401–499 → "Client Error"
- 503–599 → "Server Error"
- default → "Unknown Error".
Why
- Demonstrates switch expressions for clean mapping of HTTP status codes to human-readable messages.
- Shows advanced feature: pattern matching with when clauses for ranges.
- Provides concise alternative to large if-else chains or verbose traditional switch blocks.
How
- Used switch expression to return values directly as strings.
- Exact status codes mapped to standard HTTP reason phrases.
- Pattern-based cases handle broader ranges for grouped categories.
- Default branch ensures all other codes yield "Unknown Error".
Logic
- Inputs: integer HTTP code.
- Outputs: string description.
- Flow:
1. Match exact codes first.
2. If no match, test range-based cases.
3. If no match, fall back to default.
- Example:
- Input: 404.
- Matches case int i when i > 400 && i < 500.
- Returns "Client Error".
- Edge cases:
- Requires preview features in Java 21+ (pattern matching for switch).
- In earlier Java versions, range-based cases must be expressed with if-else or separate logic.
- Complexity / performance: O(1) branching; very efficient.
- Concurrency / thread-safety: stateless, thread-safe.
- Error handling: Default case ensures coverage for all unmatched inputs.
Real-life applications
- Converting numeric codes to readable labels (HTTP statuses, error codes).
- Replacing lookup tables or verbose branching in APIs or web frameworks.
- Useful for logging, debugging, and API responses.
Notes
- case int i when ... syntax is only valid with preview features in Java 21+; not available in Java 12–20.
- For backward compatibility, ranges can be implemented using if-else inside default branch.
- Switch expressions eliminate need for break and directly yield results.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 6a62526 commit 8575c62
1 file changed
+0
-1
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
13 | 13 | | |
14 | 14 | | |
15 | 15 | | |
16 | | - | |
17 | 16 | | |
18 | 17 | | |
19 | 18 | | |
| |||
0 commit comments