File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Use EnumSet instead of bit fields Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Use EnumSet instead of bit fields" Watch "Use EnumSet instead of bit fields" New topic

Use EnumSet instead of bit fields

Federico Minarelli

Joined: Jan 16, 2010
Posts: 29
Hello everybody!
I would like to apply the item 32 of the book "Effective Java" (i.e. "Use EnumSet instead of bit fields") to a particular case: I have to deal with an application which gives me an integer number representing the bit field from which I should build my Set..
In the old version of my class, I have something like this:

Hence, i want to now if the integer field represents a BOLD text and so on.. The improved version should use EnumSet instead of these ugly constants, but I have to face the problem that for backward compatibility I still need a reference to the integer bit fields. Here is what i wrote:

This seems to work fine.. The question is: is there a better way to do this?

Thanks a lot for your help!
Martin Vanyavchich
Ranch Hand

Joined: Sep 16, 2008
Posts: 241
I'm no expert but it looks ok to me

I no good English.
Rob Spoor

Joined: Oct 27, 2005
Posts: 19913

I'd reduce the visibility of the getValue() method as much as possible, to prevent other classes from using it instead of the enum (unless you need it elsewhere of course). You can go as far as private because private means private within the top-level class (Text). You can then even remove it and use f.value inside the constructor.

You may also want to add another constructor that takes a Collection<Flag>; you copy it to the enum set. And finally, I'd make this constructor deprecated to discourage people from using it.

How To Ask Questions How To Answer Questions
Federico Minarelli

Joined: Jan 16, 2010
Posts: 29
thank you for your suggestions guys!
I agree. Here's the link:
subject: Use EnumSet instead of bit fields