0

这可能是一个非常愚蠢的问题,但是;

如果我正在创建一个数据集,可以说,

    [WebMethod(Description = "Returns a Fruit XML")]
    public XmlElement GetALLFruits()
    {
         Fruit fruit = new Fruit();
         fruit.Name = "Mango La Ka Buma";
         fruit.expiryDate = "11/11/1911";
         getFruitCrateDetails(fruit);

         return fruit.xml; //just giving example syntax might be wrong
    }

    public void getFruitCrateDetails(Fruit fruit)
    {
         FruitCrate crate = new FruitCrate();
         crate.id = 999;

         Fruit.Crate.add(crate);

         // Now here do I need to return "Fruit" object or not ?
    }

我有 10 或 20 种方法,我应该将它们保留在方法中还是组合成 1 种大方法。

4

2 回答 2

1
[WebMethod(Description = "Returns a Fruit XML")]
public XmlElement GetALLFruits()
{
     Fruit fruit = new Fruit();
     fruit.Name = "Mango La Ka Buma";
     fruit.expiryDate = "11/11/1911";
     fruit = getFruitCrateDetails(fruit);//This is call to method 1. Don't worry your values will not be lost fruit.Name will remain as it is.


     return fruit.xml; //just giving example syntax might be wrong
}

public Fruit getFruitCrateDetails(Fruit fruit)
{
     FruitCrate crate = new FruitCrate();
     crate.id = 999;
 fruit.crate.Add(crate);//Now no other method should set crateValues
 return fruit;
}

public Fruit getFruitCrateDetails1(Fruit fruit)
{
 SomeNewProperty = "test";
 fruit.PropertyName = SomeNewProperty;//Now no other method should set value for SomeNewProperty
 return fruit;
}

请阅读评论。而且我还没有测试过代码。因此,您可能无法获得所需的输出。我已经尽力向你解释了。

于 2013-08-07T09:22:21.703 回答
0

这通常是一种风格选择,但大多数开发人员不喜欢大型方法。

通过划分方法,您可以免费获得这些东西;

  • 代码重用——您可以调用该方法两次而无需重复代码。
  • 关注点分离——我使用的一条黄金法则是,每种方法都应该按照它的名义做。复杂的方法会依次调用其他方法。

你最终得到的是一个干净的、模块化的系统,它具有一口大小的逻辑片段,可以阅读和理解,而不会让你的头脑混乱。

此外,以“get”为前缀的方法应该返回一个值。如果没有,请考虑将其命名为“添加”。这是另一种风格的事情,但如果你在一个团队中工作,它有助于将你的方法名称与方法签名相匹配。

于 2013-08-07T09:12:49.187 回答