Commit 5510b7b
committed
feat(Test1): add switch expression for HTTP status code descriptions
What
- Added Test1 class with main method printing:
- "Hello World"
- Description of HTTP status code 404 via getHTTPCodeDescWithSwitch().
- Implemented getHTTPCodeDescWithSwitch(int code) using enhanced switch expression with:
- Exact matches:
- 100 → "Continue"
- 200 → "OK"
- 301 → "Moved Permanently"
- 302 → "Found"
- 400 → "Bad Request"
- 500 → "Internal Server Error"
- 502 → "Bad Gateway"
- Pattern matching with when clauses for ranges (requires Java 21+ preview feature):
- 101–199 → "Informational"
- 201–299 → "Successful"
- 303–399 → "Redirection"
- 401–499 → "Client Error"
- 503–599 → "Server Error"
- default → "Unknown Error".
Why
- Provides clean, declarative mapping from HTTP numeric codes to human-readable descriptions.
- Demonstrates modern switch expressions with pattern matching and guards.
- Replaces verbose if-else chains with concise functional style.
How
- Used switch expression to directly return string results.
- Exact status codes handled first, ensuring most common codes map directly.
- Range cases use case int i when ... syntax to match broader categories.
- Default ensures safe fallback for any unrecognized code.
Logic
- Inputs: integer HTTP code.
- Outputs: descriptive string.
- Flow:
1. Test exact matches for well-known codes.
2. Otherwise check ranges via when clauses.
3. If none match, return "Unknown Error".
- Example:
- Input: 404.
- Not exact match.
- Matches case int i when i > 400 && i < 500.
- Returns "Client Error".
- Edge cases:
- Requires preview features in Java 21+ for pattern matching with when.
- In older Java versions, ranges must be expressed with if-else inside default.
- Complexity / performance: O(1) branching; efficient.
- Concurrency / thread-safety: Stateless method; thread-safe.
- Error handling: Default branch ensures coverage of all unexpected codes.
Real-life applications
- Converting HTTP response codes into readable text for logs, debugging, or user-facing error messages.
- Useful in API gateways, web servers, and testing utilities.
- Provides centralized mapping logic to avoid magic numbers scattered across code.
Notes
- Output for 404: "Client Error".
- Switch expressions eliminate need for break and allow direct value return.
- Guarded pattern matching makes the switch more powerful, expressive, and less error-prone.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 8575c62 commit 5510b7b
1 file changed
+24
-0
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
0 commit comments