Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Holiday Calendar 2016 (Day 22): Use Enums as Method Parameters

DZone's Guide to

Java Holiday Calendar 2016 (Day 22): Use Enums as Method Parameters

Using Enums as parameters can greatly enhance the versatility of your methods. This example shows off how Enums can be used to nimbly and simply sort your lists.

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

Image title

Today's tip is about using Enums as parameters to indicate method behavior. Let us here the fairy tail of Prince Sort and it will be more apparent why this can be a good thing.

Once upon a time there was a Prince with a sort method like this:

void sort(); // 1


Everything was good until the Prince realized he needed to sort in either direction. And so, he went about and added a boolean like this:

void sort(boolean descending); // 2


Everything was good until the Prince wanted to indicate that sorting could be done in arbitrary order. And so, he went about and changed the boolean to Boolean:

void sort(Boolean descending); // 3, null means any order


Everything was good until the Prince wanted to indicate that sorting could be done in random order too. And so, he went about and changed the Boolean to an int:

void sort(int flag); // 4, 0 = asc, 1 = desc, 2 = unspec, 3 = random


Now, the most beautiful Princess appeared out of thin air and she wore a wonderful dress and she held the most prominent PhD in computer science. The Princess told the Prince "thou shalt introduce Enums in thy methods." Here is my humble gift to you:

enum Order {
    ASC, DESC, UNSPECIFIED, RANDOM;
}


So, he went about and changed the int to the Order Enum like this:

void sort(Order order);


The Prince was delighted and promised that from now on, he would introduce Enums in step 2 and they both lived happily ever after!

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:
java ,enums ,method parameter ,sorting ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}