Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reducing Code Repetition: Calling functions with slightly different signatures

Tags:

c#

refactoring

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:

  1. I could make d an object and cast at runtype based on type, but this strikes me as not being ideal; it removes a type check which was previously happening at compile time.
  2. I could also write a private helper class that takes an object and write both signatures as public functions.
  3. I could replace dostuff and dostuff2 with delegates or function calls or something.
like image 937
Brian Avatar asked Mar 31 '10 21:03

Brian


2 Answers

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.

like image 177
Reed Copsey Avatar answered Sep 23 '22 01:09

Reed Copsey


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.

like image 40
MusiGenesis Avatar answered Sep 22 '22 01:09

MusiGenesis