2013-08-07 59 views
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种大方法结合起来。

+0

您的意思是说,在GetAllFruits中设置的水果对象会在函数被调用后添加999的Id值? –

+0

是的,因为我正在构造一个大的XML文件 – Mathematics

+0

那么在这种情况下,您将需要将返回类型设置为Fruit。而不是无效的。 –

回答

0

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

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

  • 的代码重用 - 你可以两次调用该方法,而无需复制代码。
  • 分离关注点 - 我使用的一条黄金法则是每个方法都应该这样做,就是说它的名字就是这样。复杂的方法会依次调用其他方法。

你最终什么是干净的,模块化的系统,一口大小的块逻辑的阅读和没有文字搞乱你的心的墙理解。

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

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; 
} 

请阅读评论。我还没有测试代码。所以有可能你得不到理想的输出。我尽力解释你。