This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
My problem is that I want to share enum constants throughout my program. All of the articles I've read on enums talk about HOW to write them from a syntax point of view, but not WHERE to write them. For example, should I include the enum definition in a class file? In their own file? What if I want the enum constants to be shared by source files in different packages? How to do that? Using these packages and source files as an example:
As with classes or functions or variables, you should limit your enums to the smallest scope possible - but no smaller. In your case, if you want multiple classes to use the enums then they should be accessible to all of them. So at this point you have to decide what the enums are used for. Does the enum "naturally" belong to one class and the other classes just use it (like a public method)? In this case, I would define the enum within the class. Or does the enum stand on its own where all classes just use them, in which case I would define it in its own file.
If you decide that the enum belongs in its own file, as to what package to place the enum, I would not create a separate package like com.ubm.enums because I think packages should describe functionality rather than type. (For example, I think java.util is poorly named because it doesn't describe what the classes in it actually do) If there is no obvious choice, say between com.ubm.stats and com.ubm.price then I would just pick one (flip a coin) and move on. Don't sweat it. If in a month you decided you were wrong then change it. If your IDE does not change everything automatically (Eclipse does), the compiler will tell you where you need to make changes. And if you limit the scope as previously suggested then making the changes should be trivial. If you find you cannot easily move the enum (because, for example, you are in production and you have xml files or serialized files referring to it) then just accept your previous decision, leave it where it is, and move on.