Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

program design: the right way to go?

Status
Not open for further replies.

mattyjim

Programmer
Mar 11, 2007
5
0
0
GB
hello there!


i'm new to c#, and as i'm looking to avoid developing any bad programming habits, i'd like to run my program design past all you experts just to make sure i'm not heading in the wrong direction.

can anybody see anything that might be wrong with the following idea?


i want to be able to call functions dynamically in order to avoid using large hard-coded switch statements; basically, the c# equivalent of the following vbscript code:


Code:
'this is vbscript
Execute("Call Form_" & intFormNum & "()")


at present, i achieve this by passing a dynamically built string out (from a class in an .aspx) into an external class that uses the 'Reflection' object:

Code:
/* this method calls methods that exist in other classes, based upon string representations of
the method names */

public object Run(string strClassName, string strMethodName)

{

Assembly asm = Assembly.GetExecutingAssembly();


Type type = asm.GetType(strClassName);

object obj = asm.CreateInstance(strClassName);

 

object ret = type.InvokeMember(strMethodName,

BindingFlags.Default | BindingFlags.InvokeMethod,

null, obj, null);

return ret;

}


the code works just fine, and i can invoke the methods ok, but the whole thing feels weird and a bit unnecessary.

in a nutshell, i'm using an external class to call methods that exist in the class that called the external class.
is this a normal thing to do?

if anybody could let me know whether there's an easier way of achieving my goal or not, i'd be very appreciative.



Thanks!
 
Seems like you are hard coding your method names somewhere and if you have a typo - you're screwed.

Generally, there are better ways to limit the number of calls you have to make by using some good design patterns.

Factories come to mind in terms of having similar classes that do similar things. Interfaces also help there.

To invoke every call you make via reflection does seem a bit weird to me.

Anyone Else?
 
I second JurkMonkeys opinion. In good OO designs you do not see switch statements you see polymorphism.
Reflection is an expensive operation.
I would not want to maintain what you are thinking about doing.

Marty
 
thanks for your replies!

i must admit the whole thing felt a bit nasty from the outset; i thought you might dissaprove ;-)

i'll read up on factories, interfaces and polymorphism then.


thanks for your help!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top