DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Understanding the Java Record Class With Code Examples
  • “Let’s Cook!”: A Beginner's Guide to Making Tasty Web Projects
  • Writing Great Code: The Five Principles of Clean Code
  • Hoisting in JavaScript

Trending

  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • Build Your First AI Model in Python: A Beginner's Guide (1 of 3)
  • A Deep Dive Into Firmware Over the Air for IoT Devices
  1. DZone
  2. Coding
  3. Java
  4. Enum Tricks: Featured Enum Instead of Switch

Enum Tricks: Featured Enum Instead of Switch

What's the deal with enums?

By 
Alexander Radzin user avatar
Alexander Radzin
·
Feb. 26, 19 · Presentation
Likes (23)
Comment
Save
Tweet
Share
37.0K Views

Join the DZone community and get the full member experience.

Join For Free

Problem and the Solution

Switch/case is the common control structure implemented in most imperative programming languages. Switch is considered more readable than a series of if/else.

Here is a simple example:

// Switch with int literal
switch(c) {
    case 1: one(); break;
    case 2: two(); break;
    case 3: three(); break;
    default: thrownewUnsupportedOperationException(String.format("Operation %d is not supported", c));
}


Here is the list of the main problems in this code:

  1. The relationship between int literals (1, 2, 3) and the executed code is not obvious.
  2. If one of the values (e.g. 2) is not supported anymore and this switch is not updated accordingly, it will forever contain the unused code.
  3. If a new possible value of c (e.g. 4) is introduced and the switch is not updated accordingly, the code will probably throw the UnsupportedOperationException at runtime without any compile time notifications.
  4. Such a switch structure tends to be duplicated several times in code that makes problems 2 and 3 even more complicated.

The simplest fix can be done by using int constants instead of literals. First, let's define constants:

private static int ONE = 1;
private static int TWO = 2;
private static int THREE = 3;


Now, the code will look like this:

switch(c) {
    case ONE: one(); break;
    case TWO: two(); break;
    case THREE: three(); break;
    default: thrownewUnsupportedOperationException(String.format("Operation %d is not supported", c));
}


Obviously, in real life, the names of the constants must be self-descriptive. This snippet is more readable but all other disadvantages are still relevant. The next attempt to improve the initial code snippet uses enums introduced to Java language in version 5 in 2004. Let's define the following enum:

enum Action {ONE, TWO, THREE}


Now, the switch snippet will be changed slightly:

Action a = ...
switch (a) {
    case ONE: one(); break;
    case TWO: two(); break;
    case THREE: three(); break;
    default: thrownewUnsupportedOperationException(String.format("Operation %s is not supported", a));
}


This code is a little bit better: it will produce compilation error if one of the elements is removed from enum Action. However, it will not cause a compilation error if an additional element is added to enum Action. Some IDEs or static code analysis tools may produce a warning in this case, but who is paying attention to warnings? Fortunately, an enum can declare an abstract method that has to be implemented by each element:

enum Action {
ONE { @Override public void action() { } },
TWO { @Override public void action() { } },
THREE { @Override public void action() { } },
public abstract void action();


Now, the switch statement can be replaced by single line:

Action a = ...
a.action();


This solution does not have any of disadvantages enumerated above:

  1. It is readable. The method is "attached" to enum element; one can write as many javadoc as it is needed if method meaning is unclear. The code that calls method is trivial: what can be simpler than method invocation?
  2. There is no way to remove an enum constant without removing the implementation, so no unused code will remain if some functionality is no longer relevant.
  3. A new enum element cannot be added without the implementation of method action(). Code without implementation can't be compiled.
  4. If several actions are required, they can all be implemented in the enum. As we already mentioned, the code that calls specific function is trivial, so now there is no code duplication.

Conclusion

Although switch/case structure is well known and widely used in various programming languages, its use may cause a lot of problems. The solution that uses Java enums and described above does not have these disadvantages. The next article from this series will show how to extend the functionality of an existing enum.

Java language Coding best practices

Published at DZone with permission of Alexander Radzin. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Understanding the Java Record Class With Code Examples
  • “Let’s Cook!”: A Beginner's Guide to Making Tasty Web Projects
  • Writing Great Code: The Five Principles of Clean Code
  • Hoisting in JavaScript

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!