Day 22, Java Holiday Calendar 2016, Use Enums as Method Parameters
Today's tips 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 already 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. I am contributing to open-source Speedment, a stream based ORM tool and runtime. Please check it out on GitHub.