java - Good way of calling Functions/class in big if/else constructs -
i've seen many code-parts in old(java mostly) projects
if(type == typeone){ callfunctionone(); }else if (type == typetwo){ callfunctiontwo(); }else if (type == typethree){ callfunctionthree(); }//i've seen on ~800 lines this!
where "type" enum or , whole thing written in switch/case style too. question is: there "better"(more stylish/shorter/more readable) way achieve this? i've seen constructs in php like:
//where $type = "one","two" etc. $functionname = 'callfunction' . $type; new $functionname();
but im not sure if realy "better" way , if possible in other languages.
the more interesting question imo want achieve this?
java object-oriented language. therefore solve 1 subclass per type:
abstract class type{ abstract void method(); } class type1 extends type{ void method(){ //do sth. specific type } }
if methods in same class still call them out of these classes passing (i see ugly).
class randomclass(){ void method1(){ //do sth type1 } void method2(){ //do sth type2 } } abstract class type{ randomclass randomclass; type(randomclass randomclass){ this.randomclass = randomclass; } abstract void method(); } class type1 extends type{ void method(){ randomclass.method1(); } } class type2 extends type{ void method(){ randomclass.method2(); } }
otherwise use reflection, suggested sohaib (example taken suggested link):
yyyy.class.getmethod("methodname").invoke(someargs)
but using reflection somehting seems unhandy inperformant , nice trap later maintenance (just imagine starts renaming methods).
so answer question (at least how understand it):
dynamically calling methods e.g. determining name dynamically @ runtime, in scripting languages. object-oriented approach might come overhead, @ end better style kind of language.
if both solutions not work you, switch statement or if-else cascade best alternative.
Comments
Post a Comment