This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

eliminating duplicate Enum code

 
Dan Murphy
Ranch Hand
Posts: 126
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a large number of Enums that implement this interface:



A typical example is:



As you can imagine these methods are virtually identical in all implementations of CodableEnum. I would like to eliminate this duplication, but frankly don't know how. I tried using a class such as the following



But this turns out to be fairly useless because:

1. An enum cannot extend a class
2. Elements of an enum (SKYPE, GOOGLE_TALK, etc.) cannot extend a class
3. I cannot provide a default implementation of getByCode(), because DefaultCodableEnum is not itself an Enum. I tried changing DefaultCodableEnum to extend java.lang.Enum, but this doesn't appear to be allowed.

Any suggestions?
Thanks,
Dan Murphy

[ June 11, 2008: Message edited by: Dan Murphy ]
[ June 11, 2008: Message edited by: Dan Murphy ]
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any reason you don't use the predefined toString and valueOf methods?
 
Dan Murphy
Ranch Hand
Posts: 126
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, the correct functioning of my program depends on these codes, whereas the contract of toString() indicates that the value returned by this method is "for a person to read". Therefore it should be possible be to change the value returned by toString() without breaking anything, which is why I prefer to use the value returned by toString() for logging/debugging purposes only.

More specifically, if I were to use the built-in toString() and valueOf() methods, then my program would no longer work after renaming an element from say YAHOO_MESSENGER to YAHOO_MGR.

[ June 12, 2008: Message edited by: Dan Murphy ]
[ June 12, 2008: Message edited by: Dan Murphy ]
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In that case, I don't think you can remove the duplication by using inheritance. The only two options I see are reducing the duplication by having the enum methods delegate to some helper class, and/or using code generation to generate the complete enum source code.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic