tags:

views:

133

answers:

5

What is the difference between these two cases. Firstly, if I open the connection and pass it into my method as a parameter, 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
}
+2  A: 

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.

Paddy
There is a huge difference in the expectation of the methods being called in the two scenarios.
Filip Ekberg
Quite - it's not terribly clear from the method signature what is meant to be done - the method would better checking if the connection is open, opening and closing it not, and just using it otherwise. When I say there is no difference, I mean from a general functionality point of view.
Paddy
A: 

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.

Filip Ekberg
A: 

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.

Rodrick Chapman
A: 

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.

Adrian Regan
A: 

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.

Mubashar Ahmad