减少代码重复:调用具有略微不同签名的函数

Bri*_*ian 7 c# refactoring

假设我有两个看起来像这样的函数:

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
}
Run Code Online (Sandbox Code Playgroud)

什么是避免重复dostuff的好方法?

我想过的想法,但不喜欢:

  1. 我可以根据类型制作一个对象并按照runtype进行投射,但这让我觉得不理想; 它删除了以前在编译时发生的类型检查.
  2. 我还可以编写一个私有帮助器类,它接受一个对象并将两个签名都写为公共函数.
  3. 我可以用委托或函数调用等替换dostuff和dostuff2.

Ree*_*sey 6

只需将"doStuff"和"doStuff2"重构为单独的方法即可.

他们显然做的"东西"与"personelsesfunction"方法分开,所以它们应该是不同的方法.理想情况下,每种方法都应该有一个任务.

这甚至是Visual Studio中支持的重构 - 只需突出显示"dostuff"中的代码,然后右键单击,然后选择Refactor-> Extract Method.


Mus*_*sis 4

我可能会做这样的事情:

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);      
}
Run Code Online (Sandbox Code Playgroud)

...并将两个函数的名称更改为MyFunction( 以利用重载,这是同一件事someoneelsesfunction()

注意:如果流中包含的字符串非常大,则此解决方案将不切实际。如果是这样,您可能想以相反的方式执行此操作:将字符串读d入流并使用流参数调用覆盖。