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 refactoring the class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "refactoring the class" Watch "refactoring the class" New topic

refactoring the class

Mohit Sinha
Ranch Hand

Joined: Nov 29, 2004
Posts: 125
Hi there,

Currently I have a class which is kind of a factory implementation. The way it works is it has an Enum something like this
static Enum Variables {ABC LMN PQR XYZ};
This class has a method which has create method like this
private IVariable(String varName)
IVariable obj = null;
Variables val;

try {
val = Variables.valueOf(varName.toUpperCase());
case ABC:
obj = new VariableABC(); break;

case LMN:
obj = new VariableLMN(); break;

case XYZ:
obj = new VaraibleXYZ(); break;



I want to discard this switch case approach and go for alternatives I guess (reflection will be most appropriate). Do post your comments on what approach should i opt for in the above scenario.

Adam Teg
Ranch Hand

Joined: Feb 09, 2006
Posts: 36
You can pass in the Class.class and return the needed type.
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
I'd stay away from reflection unless you really need it, and in this case I'm almost certain you dont. I guess this is a made-up example and not real code because there are a few things there that just don't make sense. Regardless, one solution would be to let the enum instance itself create the variable:

[ September 15, 2008: Message edited by: Garrett Rowe ]

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Mohit Sinha
Ranch Hand

Joined: Nov 29, 2004
Posts: 125
Hi Garrett

Thanks for the info and apologize for the unclear question. Why I mentioned about a dynamic approach was there could be 500 such variables and I don't want to repeat the same operation over and over again.

Is there such an option available.

Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

Then why not just use the static "valueOf" method of the Enum class which takes a String and returns the enum value which corresponds to that string? No reflection required. Not even a switch statement required.
Rob Spoor

Joined: Oct 27, 2005
Posts: 20271

And you need a VariableXYZ for each enumeration value anyway, so why not put that code in the enumeration itself? That way, if you add a new item to the enumeration, all your other code immediately works.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: refactoring the class
jQuery in Action, 3rd edition