• Post Reply Bookmark Topic Watch Topic
  • New Topic

Enums : Is it a useless wonder ?  RSS feed

 
Ranch Hand
Posts: 43
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am in java development from long time and also in java 1.5 from more than 3 years.
Recently in a seminar i saw people are using java enums, that day i realized i never used enums in my code(projects) .
i told same to my friend and he answered me, "enum is a useless wonder !"

I said, come on ! it added in Java 5 release, can you imagine to write a code today without generics and without using annotations.
enum is brother of these great worriers, their must be some great use of it, we just need to to so some R&D.

from that day and till today, i am still waiting for that "great use" !

Let me allow to describe some use which i felt could be great but they wasn't

1) To use a static collection of constants.
sol : it is far easier and better to use a class with static members, why should i learn new thing ?
using class i get the flexibility to define type of constant also !

2) No type definition needed.
sol : its a advantage or disadvantage ?

3) can use as new generation way to define singleton class.
sol : sounds good ! and may have some advantage, but i am using old school singleton pattern from long time, so far no problem !
easy to use and understand.

and after big time R&D and googling i come to the conclusion, i have not use enums so far as i did't need it
Be frank, no body at no where need it.

If somebody disagree with my comment, please add yours !
 
Sheriff
Posts: 21137
87
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes you can emulate most of the enum functionality with static final fields of the same type. In fact, I've written enums for Java 1.4 in exactly such a way. However, you need to do quite a few things manually which you get for free with enums:
- the name() method
- the static valueOf(String) method
- the static values() method
- being Comparable
- being Serializable
- default implementation of toString()

These can all be achieved with other code. But here's where the "most" comes into place. Finish your enum look-a-like class. Now try implementing a switch statement for that class. Not so easy, is it? The only way is to use a static final int for each static final instance; that's two fields instead of one. And you must ensure yourself that these static final ints are unique within the class. Add one field in the middle and your numbering will either be non-sequential, or you have to renumber a lot of fields.

I'll choose enums over look-a-like classes any day.
 
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I use enums all the time -- I hardly find them "useless wonders". They are perfect for modeling fixed collections. Just because your friend doesn't find a use for them doesn't make them useless for everyone.

I've never used a scalpel -- does that make it a useless tool?
 
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Switch statements and methods are really, really useful. I like enums.
 
Bartender
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On the other hand one could make an argument to just stick with assembly or machine language. Everything else is syntactic sugar. ;)
 
Praveen Kumar Singh
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Rob, great points.

may be in my look-a-like case i will go for if-else blocks in place of switch block

For your other points, my comments are following

- being Comparable : don't see any value in this if my class has only string or int ! for rest of the rare case i will implement it.
- being Serializable : need to add just one more interface
- default implementation of toString() : totally useless, all built in data type in java has same.
- the name() : i don't see much advantage and use.

- the static values() method : yes this is useful as we don't have any way to iterate over class variables other than reflection.

Actually, what i am interested in, is the 'the point' which force me to use enums !
From your statements, i am convince their is use of enums, as set of tokens,
right now, for me, enums are more like good looking easy to handle array.

but to use as datatype to store just static constants, still no reason to use enums.
same for singleton also.


 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe you don't see it now, but you will. There's almost no reason to code your own fake enums any more, ever.
 
Praveen Kumar Singh
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi David,

i know the great sun java(or oracle java) has added this feature because of some reason
i am just having hard time to understand when, where and why !
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Some good reasons were already enumerated--you're just happy doing things by hand that a lot of people would rather do with existing language constructs. I have better things to do than re-implement a portion of existing functionality that doesn't do as much, that's all.
 
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I may be wrong here, but to me, it sounds like when Rob and David talk about alternatives to using modern enums, they're referring to using the classic type-safe enumeration pattern. And when Praveen talks about alternatives, he's talking about something more basic, like this:

So Praveen may be wondering how an enum is better than this. Well, consider a method that uses these Suits values as a parameter:

If I want to use this method, how do I know what values I can put in it? Nothing in the signature gives me any clue. If I put in a value like 0 or 5, the compiler will not complain. The code may crash later when I run it, or not. Hard to say. With this code, the author of the display() method really needs to write a good JavaDoc comment explaining the possible values. And clients need to read it. And you can't rely on the compiler to tell you if you do something wrong.

Now consider the equivalent with enums:

With this code, anyone who looks at the display() method knows that the argument must be a Suit. Their IDE can immediately let them auto-complete any of the four legal values for this method, and the compiler will prevent them from using any illegal value. To me, that's a big benefit for using an enum rather than public static final ints, or Strings.
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're right, I had assumed the OP was referring to the old-school enum pattern, primarily for the type-safety reason. Sometimes I think too far ahead, I guess.
 
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well i am not an "Experienced " java programmer. I have been in the industry for just one year. However, my Masters thesis is in Object Relational Mapping and paradigms and this is where i have a little insight into the whole languages field.
Based on this experience i would like to point out a few things.

Enums are an important tool provided by languages to emulate real life functionality which even though possible with scores of alternatives is not something which is efficient.
A classic example i can give you guys is Generics. You can have type checking for every field of your choice, but generics added an extra provision in the language as opposed to enums.

The reason why this question came up is because Java creators failed to incorporate enums in their own code. A classic example i can give is lets assume you are writing a code for a particular object which has various states. For the sake of example, lets assume, we are talking about the database connection object. Let us assume It can have states like connected, connecting, disconnected and disabled.

In this case java has used the way of using integers to define states. This has made java code much much less readable. Not to menention confusing. .Net on the other hand has used enums in this place.


in java you write
if(connObject.state == 4)
dosomething()



same in .net you would write
if(connObject.state == ConnectionState.Open)
dosomething();


This is just one example. Another very useful place i liked the .net use of enums is file open flags.
In java
new RandomAccessFile(new File("Filename"),"Write");
the "RW" part looks untidy and error prone.

in .NET


file f = File.Open("filename",Filemode.ReadWrite);


To sum it all, it is like a drop down menu for coding. Even though textboxes with limited allowable characters can serve the purpose, Enums are a much more sleek and robust way to go


Hope this helps
 
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gaurav Raje wrote:In java
file.open("Filename","RW");
the "RW" part looks untidy and error prone.
Is that real Java code? I couldn't find an open(String, String) method in the API index. That looks more like C code to me.
 
Gaurav Raje
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:
Gaurav Raje wrote:In java
file.open("Filename","RW");
the "RW" part looks untidy and error prone.
Is that real Java code? I couldn't find an open(String, String) method in the API index. That looks more like C code to me.


yup you are right

it is actually file.open(new File("filename"),"write");
where file is a randomaccessfile object

i mixed the c code... just goes on to provvve my point on how confusing it becomes with strings instead of enums and usefulness of enums
 
Campbell Ritchie
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I still can't find an open method in RandomAccessFile. As you said, you are quoting C or C++.
 
Gaurav Raje
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
edited... its the constructor i am talking about
 
Ranch Hand
Posts: 173
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

This argument can be extended to almost all aspects.

Maybe the extent to which we use these Enums can properly justify their inclusion.

When your switch construct goes from 2 to 10 cases OR 2-5 of your team members fight out for the same value

We might not see the value they create, but that is not true for all situations.

I find they are more organized than what mundane programmers could have achieved trying to implement the same.

Again, hats off to all you guys who have successfully implemented their own, but they still will be
useful to many in the Java Developer community.

 
Praveen Kumar Singh
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Mike,
Great point, this is what i was looking at, benifits what you can justified.
thanks man for your comment !
 
Rob Spoor
Sheriff
Posts: 21137
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Praveen Kumar Singh wrote:- being Serializable : need to add just one more interface

That's the naive approach. Try the following:
Not what you want from an enum, right? Like I said before, enums do so much for you in the background.
 
Praveen Kumar Singh
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob !
For rest of followers, who didn't get anything here
do theses changes in EnumWanabee class

class EnumWanabee implements Serializable {
public static final EnumWanabee ONE = new EnumWanabee();

private EnumWanabee() {
}

private Object readResolve() throws ObjectStreamException {
return ONE ;

}
}

method readResolve() is needed to hold object uniqueness over network.
Yes having "vice-versa" with two static members in above case will spoil the party !
Then only enum can save us !
 
Rob Spoor
Sheriff
Posts: 21137
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
Praveen Kumar Singh
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Rob, i updated my last post
Want to add something ?
 
Campbell Ritchie
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What did you change? Changes to posts made after a reply can change the reply to nonsense.
 
Praveen Kumar Singh
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Campbell,
i just changed my post @ posted Today 6:57:43 PM (Actually just added something)
Don't get emotional
 
Campbell Ritchie
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Praveen Kumar Singh wrote:Hi Campbell,
i just changed my post @ posted Today 6:57:43 PM (Actually just added something)
Don't get emotional
I won't, but you should see the sort of changes some other people make to posts, which make the whole thread read as nonsense.
 
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Praveen:

Another reasonable use for enums is when you're implementing the flyweight pattern.

John.
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hm, I find it a bit annoying to have to go back and re-read a post I've read before, just to figure out what has been changed. To me it seems much easier for everyone if new information appears sequentially - if you've got something to add, put it at the end.

But I did see one thing that deserves comment:
Praveen Kumar Singh wrote:Yes having "vice-versa" with two static members in above case will spoil the party !
Then only enum can save us !

Well, no, there are certainly ways to handle this. Basically your instances need to have some internal data that allows us to identify which is which. For example:

Or perhaps:

Anyway, this sort of thing is certainly possible without enums. But it's all code that we just don't need anymore, now that the enum keyword gives us all that stuff for free.
 
Rob Spoor
Sheriff
Posts: 21137
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Praveen added the code with readResolve, which is indeed the method to use to prevent the problem in my code.

Mike, you should move the private static List (which should be final!) up; it must be initialized before the three instances or they will throw NullPointerExceptions from their constructors because the list is still null.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!