Why Enums Are Considered Poor Choices for API Return Values
The article explains why using enums as API return values is often criticized, highlighting their lack of extensibility, potential serialization errors when newer enum values appear, and contrasting this with the safety they provide as input parameters, illustrated with Java examples and community opinions.
Question
A colleague complained that using an enum in an interface definition was strongly disliked because it is hard to extend.
The discussion starts by quoting Alibaba's development manual, which gives recommendations on enum usage.
What the Manual Says
The manual supports defining and using enums, yet it appears to oppose using enums as return values.
Author's Explanation
Due to version upgrades, the enum classes on both sides may differ, causing deserialization exceptions during interface parsing. Enums have advantages such as type safety, clarity, equality checks, and suitability for switch statements, but their main drawback is that they cannot be extended.
When an enum is used as a parameter, the caller can only send values that the provider already knows, which is safe. However, when an enum is used as a return value, the provider may introduce new enum constants that the caller's local enum does not contain, leading to serialization errors.
For example, a local enum Weather { SUNNY, RAINY, CLOUDY } might be used in a method guess(Weather w). If the remote side later returns SNOWY, which is not defined locally, deserialization fails.
Another Community Answer
Another user explains that an enum simply lists all known values. As an input, it guarantees safety because callers can only send supported values. As a return value, the provider decides which values are possible; after an upgrade, new values may appear that the caller does not recognize, making the API brittle and prone to exceptions.
(End)
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
