- Completeness checks on enums using JDK 21+ switch statements
- See this approach implemented in production
- About
When maintaining APIs with multiple clients and endpoints, how can you ensure consistency between the query parameters defined on the server and those implemented by clients?
A common solution is to document and maintain APIs using the OpenAPI specification, implemented by many frameworks. However, if you’re looking for a simpler, framework-free alternative, recent Java language features offer built-in support to ensure consistency through exhaustiveness checks on enums in switch statements.
From JDK 21 onwards, the Java compiler enforces exhaustiveness checks in switch statements involving enums. This means the compiler will raise an error if an enum value is omitted from a switch statement.
This feature ensures consistency: if you modify the query parameters on the server but forget to update the client, the client-side code will not compile, serving as an effective safeguard.
Here’s a practical example:
Defining an enum for your query parameters
Place this enum in a shared module accessible by both the server and client:
Client-side implementation
Loop over the enum values to add query parameters to your request:
What happens if a parameter is omitted?
If you forget to handle a parameter, such as “PRECISION,” the compiler will issue an error:
My IDE (NetBeans) provides a helpful warning explaining the issue:
Server-side implementation
The server-side code follows the same principle. It will also generate compiler errors if any enum values are missing in your switch statements.
Here’s an interesting server-side twist: in my application, query parameters are parsed into values set within a workflow object. To maintain the exhaustiveness checks while parsing parameters, ChatGPT suggested the elegant solution of using a Consumer:
I am currently refactoring nocodefunctions.com to implement this approach. Check:
- the repo for the frontend of the app, which builds requests sent to the microservices
- the portal for microservices, receiving these requests
- the module shared between the frontend and the portal
I’m an academic and independent web app developer. I created nocode functions 🔎, a free, point-and-click tool for exploring texts and networks. It’s fully open source. Try it out and let me know what you think—I’d love your feedback!
- Email: [email protected] 📧
- Bluesky: @seinecle 📱
- Blog: Read more articles 👓 on app development and data exploration.
.png)


