This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
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
Joined: Feb 09, 2006
Posts: 36
posted
0
You can pass in the Class.class and return the needed type.
Garrett Rowe
Ranch Hand
Joined: Jan 17, 2006
Posts: 1295
posted
0
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
posted
0
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.
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.
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.