Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

refactoring the class

 
Mohit Sinha
Ranch Hand
Posts: 125
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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());
switch(val)
{
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.

Regards,
 
Adam Teg
Ranch Hand
Posts: 36
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can pass in the Class.class and return the needed type.
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Mohit Sinha
Ranch Hand
Posts: 125
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Thanks
 
Paul Clapham
Sheriff
Pie
Posts: 20187
26
MySQL Database
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 20381
46
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic