开发者

What is difference between this two C# methods

What is the difference between these two cases. Firstly, if I open the connection and pass it into my method as a param开发者_如何学Goeter, compared to opening the connection directly in the method?

cnn.open()
func(cnn,param1,param2);

vs

func(cnn, param1,param2)
{
  cnn.open();
  //open connection here
}


There's no difference from the code you've posted other than in one case, your calling function needs to take care of opening/closing the connection, in the other, you'd expect the function to do it.


The difference is that in the second method, you open the connection.

In the first method you expect the method to only use a connection not caring about cleaning up the resources.


No functional difference but the lines for opening and closing a connection should usually be as close together as possible hence they should be in the same method.


The difference is in how you want to use the connection and performance. If the function is a once off call and you are calling no other functions, or not doing anything else with the connection, then the second version of the function could even be reduced to:

func(param1, param2) {
    Connection c = ....
    c.Open(...);
    ...
    c.Close();
}

However if you are calling many functions on the connection, even calling the function many times on the connection or if the creation and configuration of the connection is at a higher layer in your code, then you should use the first version of the function, with the addition of throwing an exception if the connection is not opened.


Well, I think you shouldn't ask for the different rather you should explain the situation you are in and ask for recommendation for what case must be used.

Anyway, As Everybody told you In case 2 the connection object and its life cycle is encapsulated within the callee function. This is recommended if database operation out side this function is not desired.

Otherwise if you have any other database activity to be done out side this function scope like in caller function or any other function(other than func) being called from caller function then you should use the Case 1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜