0

有时我必须在课堂上编写大代码,所以我所做的是这样的,

Class ABC   //it's a web service class
{
   Public void Method-1() //used "-" for easy to read
   {
       //DoSomething and get something from database
       Method-2(pass parameters that i got from database);  
   }

   Public void Method-2(parameters)
   {
       DoSomething again and get data from another database. and some other source
       do some processing by calling web services (just as example)
       Method-3(parameter);
   }

   Public void Method-3(parameters)
   {
       DoSomething again and get data from another database. and some other source
       do some processing by calling web services (just as example)
       Method-4(parameter);
   }

   // and it keeps going
}

另一种方式

Class ABC   //it's a web service class
{
   Public void Method-1() //used "-" for easy to read
   {
       Method-2();
       Method-3();
       Method-4();
       // so on....
    }
}

这是正确的做法吗?如果不是,那么最好的做法是什么?

编辑

@Sayse我正在尝试从不同来源获取信息并尝试构建一个大的XML文件,这使我可以使用4、5个foreach循环从sql等中获取数据。所以使用嵌套方法

4

4 回答 4

2

Both ways are good in different cases. If you have single functionalities, you should keep them separate. Second approach - calling method from method should be used when one method is part of 'outer' functionality.

Examples:

repairVehicles() {
    repairCar();
    repairBike();
    repairTrain();
}

... but:

repairCar() {
    ...
    repairEngine();
    ...
}

repairEngine() {
    ...
    takeEngineOut();
    ....
}

takeEngineOut() {
    ...
    unscrewBolts();
    ...
}
于 2013-08-29T09:06:03.587 回答
1

据我了解您的问题,您所描述的基本上是一个管道。有一个非常有趣的博客(这里这里分为两部分)关于如何优雅地处理你的情况。

于 2013-08-29T09:47:42.727 回答
1

你的问题不可能有一个直截了当的答案。

首先,您应该注意一种方法应该执行一种功能。如果它是真的,那么你可以根据你的要求来调用它。

例子:

如果您有基本方法,则将数学表达式作为输入。该表达式包含加、减、乘和除,然后您将其称为第一种方式。

public int GetExpressionResult(string someExpression)
   {
         Divide();
         Multiply();
         Addition();
         Subtraction();
        return result;
   }

在上面的示例中,结果取决于所有四种方法,因此可以这样调用它。

现在在您的示例 2 中,如果这些方法彼此完全独立,而不是您应该采用的方式。

结论:

对此没有硬性规定,您应该按照应用程序要求的方式调用。

于 2013-08-29T08:56:03.290 回答
0

At the end, it depends on what you're trying to do and applies, IMHO, not only to C#.

Your first option should be applied when method<i+1> is a helper for method<i>, or is included in it. I can't find an example for such a scenario.
Your second example, which is far more readable to me, should be applied when you have a long sequence of actions that need to take place. Let say:

void mainMethod()
{
    ConnectToDB(); //if can't connect, log it and exit
    GetUserInfo(...); //if null, log it and exit
    ShowUserInfo(...); 
}

In the example above, it's hard (for me) to imagine a division to methods like in your first scenario.

于 2013-08-29T09:03:09.633 回答