I need a method to effectively search strings for specific patterns, and changing the string based on the pattern that is found. Right now, my solution works, but I'm not happy with it at all due to a high cyclomatic complexity. What I've got is like this:
foreach (string test in string[] strings)
{
if (test.Contains("one")
{
test = ExecuteCodeOne(test);
}
if (test.Contains("two")
{
test = ExecuteCodeTwo(test);
}
if (test.Contains("three")
{
test = ExecuteCodeThree(test);
}
if (test.Contains("four")
{
test = ExecuteCodeFour(test);
}
if (test.Contains("five")
{
test = ExecuteCodeFive(test);
}
}
Each of the ExecuteCode methods executes different code, with one thing in common: they all call a version of test.Replace("some value", "some other value")
. As you can see, this doesn't look ideal. I'd like to refactor this to something better. My question is: is there a design pattern I'm missing and could use to reach a lower complexity and hopefully lower execution time?
EDIT: An example of the ExecuteCode methods:
private static string ExecuteCodeOne(string test)
{
return test.Replace("value1", "newValue1");
}
private static string ExecuteCodeTwo(string test)
{
if (test.Contains("Value2"))
{
test = test.Replace(new Regex(@"Regex1").Match(test).Groups[1].Value, "");
test = test.Replace("Value2", "");
}
else if (test.Contains("Value3"))
test = test.Replace("Value3", "newValue3");
return test;
}
So, the private methods do vastly differing things, including their own checks, but in practice always leading to a form of String.Replace().