问题描述
我有一个关于将对象传递给方法或使用键值在方法中创建对象的问题。哪种方法更好?
请考虑以下代码。在BuilderOrder类中,有一个名为GenerateKey的方法,它需要访问BuilderMaster对象。将BuilderMaster对象直接作为参数传递给方法或传递键值并在方法中创建BuilderMaster对象是一个好主意。
I have a question regarding passing object to method or creating an object within the method using key value. Which is a better approach ?
Consider below code. In BuilderOrder class there is a method called GenerateKey which needs to access BuilderMaster object. Is it a good idea to pass BuilderMaster object directly as a parameter to the method or pass key value and create BuilderMaster object within method.
public class BuilderMaster
{
public DTO.BuilderMaster GetBuilderMaster(string systemNo)
{
// rerurn builderMaster object
}
}
public class BuilderOrder
{
//Option 1 : Pass systemNo value from UI and create object .
public bool GenerateKeys(string systemNo,int noOfKeys)
{
BuilderMaster objBuilderMaster = new BuilderMaster();
DTO.BuilderMaster objThisBuilder = objBuilderMaster.GetBuilderMaster(systemNo);
//use objThisBuilder's properties during key generation process.
}
//Option 2 : Pass object from UI
public bool GenerateKey(DTO.BuilderMaster objThisBuilder, int noOfKeys)
{
//use objThisBuilder's properties during key generation process.
}
}
选项1产生紧耦合,而选项2则没有。
现在考虑GenerateKey是由Web服务公开的方法,该服务由在不同计算机上运行的Web应用程序调用。与选项2相比,选项1创建了一个更轻的请求对象,如在选项1中,您只传递基本类型,而在选项2中,您传递的是整个构建器主对象。
哪一个更好的方法?
Option 1 creates tight coupling while Option 2 does not.
Now consider GenerateKey is method exposed by a web service which is being called by a web application running on a different machine. Option 1 creates a lighter request object compared to option 2 as in option 1 you are only passing primitive types while in Option 2 you are passing a whole builder master object.
Which is a better approach ?
推荐答案
这篇关于哪个选项更好 - 将对象传递给方法与否?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!