Suppose I have two functions which look like this:
public static void myFunction1(int a, int b, int c, string d)
{
//dostuff
someoneelsesfunction(c,d);
//dostuff2
}
public static void myFunction2(int a, int b, int c, Stream d)
{
//dostuff
someoneelsesfunction(c,d);
//dostuff2
}
What would be a good way to avoid repeated dostuff?
Ideas I've thought of, but don't like:
Just refactor "doStuff" and "doStuff2" into separate methods.
They're obviously doing "stuff" that's separate from the "someoneelsesfunction" method, so they should be separate methods anyways. Each method should have one task, ideally.
This is even a supported refactoring in Visual Studio - just highlight the code in "dostuff", and right click, and choose Refactor->Extract Method.
I might do something like this:
public static void myFunction1(int a, int b, int c, string d)
{
//dostuff
someoneelsesfunction(c, d);
//dostuff2
}
public static void myFunction2(int a, int b, int c, Stream d)
{
string str = d.ReadEntireString(); // no such method, but basically
// whatever you need to do to read the string out of the stream
myFunction1(a, b, c, str);
}
... and change the name of both functions to MyFunction
(to take advantage of overloading, which is the same thing someoneelsesfunction()
is doing.
NOTE: this solution would be impractical if the string contained in the Stream is ginormous. If so, you might want to do this the other way around: read the string d
into a stream and call the override with the stream parameter.
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