假设我有两个看起来像这样的函数:
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的好方法?
我想过的想法,但不喜欢:
只需将"doStuff"和"doStuff2"重构为单独的方法即可.
他们显然做的"东西"与"personelsesfunction"方法分开,所以它们应该是不同的方法.理想情况下,每种方法都应该有一个任务.
这甚至是Visual Studio中支持的重构 - 只需突出显示"dostuff"中的代码,然后右键单击,然后选择Refactor-> Extract Method.
我可能会做这样的事情:
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入流并使用流参数调用覆盖。
| 归档时间: |
|
| 查看次数: |
396 次 |
| 最近记录: |