Currently am doing a college project in C# which includes conversion of one form of code to another form of code, which involves choosing appropriate method/function from many methods available. The problem here is, to implement this using any pattern matching techniques rather then using many IF ELSE statements.
For now I have achieved this using nested IF ELSE statements which fills the whole program and looks like childish code on completion.
Current Implementation :--
Input:
//stored in list<string>
get(3 int) //type1
get(int:a,b,c) //type2
get(name) //type3
//list passed to ProcessGET method
Using if else :
public string ProcessGET(List<string> inputData)
{
foreach(var item in inputData)
{
if (inputData.item.Split('(')[1].Split(')')[0].Contains(':'))
{
return Type2 result;
}
else if (!inputData.item.Split('(')[1].Split(')')[0].Contains(':') && Convert.ToInt32(inputData.item.Split('(')[1].Split(')')[0].Split(' ')[0])>0)
{
return Type1 result;
}
else
{
return Type3 result;
}
}
}
How I wanted this to be is something like this,
/stored in list<string>
get(3 int) //type1
get(int:a,b,c) //type2
get(name) //type3
//list passed to ProcessGET method
public string ProcessGET(List<string> inputData)
{
foreach(var itm in inputData)
{
// call appropriate method(itm) based on type using some pattern matching techniques
}
}
string Method1(var data)
{
return result for type1;
}
string Method2(var data)
{
return result for type2;
}
string Method3(var data)
{
return result for type3;
}
Normally my program does mostly this kind of work for various types of input keywords like 'get','output','declare' etc etc etc... where Get is transformed to Scanf statements,output to printf statements and so on. In such case if i use the IF ELSE, my project is full of If else statements.
As i just started to learn C#, I don't know if such thing exists(googled but didn't found what i was looking for), so any help regarding this problem will be very help(use)ful in further development.
Many Thanks in Advance.
Another general approach to this problem is to introduce an interface, say IMatcher. The interface has one method Match that returns either your type or maybe the fully transformed line.
You create multiple classes that implement IMatcher.
Your main loop then becomes:
var matchers = new [] { new MatcherA(), new MatcherB(), ... };
foreach (string line in input)
foreach (matcher in matchers)
{
var match = matcher.Match(line);
if (match != null) return match;
}
No more big if statement. Each matcher has its own small class and you can write unit tests for each. Also, use RegEx to make your matchers simpler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With