Reputation: 254944
Let's suppose I have such "helper" methods used by some object.
private int MatchRegex(string regex, string input)
{
var match = Regex.Match(input, regex);
return match.Success ? Convert.ToInt32(match.Groups[1].Value) : 0;
}
private string Exec(string arguments, string path = "", bool oneLine = false)
{
var p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
if (path != "")
p.StartInfo.WorkingDirectory = path;
p.StartInfo.FileName = "binary.exe";
p.StartInfo.Arguments = arguments;
p.Start();
string output = oneLine ? p.StandardOutput.ReadLine() : p.StandardOutput.ReadToEnd();
p.WaitForExit();
return output;
}
Which would you choose to move out them: another class, partial class or extension methods? And why?
Upvotes: 1
Views: 375
Reputation: 1062975
If they accessed private state they would have to be methods in a partial class fragment. Extension methods are useful it it can support a range of objects, or the type can't be used as a partial class (an interface being the most likely example, or outside of your assembly).
Looking at those methods, they don't really seem to relate to any given object, so I would do neither, and just expose them as static methods on a utility class. For example:
public static class ProcessUtils {
public static string Exec(...) {...}
}
The regex one is a different case; obtaining group 1 as an int seems such a specific scenario (unless there is something domain-specific in your project that makes this common-place), and the code is so trivial, that I would just let the calling code use the existing static Regex.Match
. In particular, I would want the caller think about whether a static pre-compiled regex might be appropriate, which your utility method doesn't allow.
Upvotes: 3