I ran across this bit of code (not mine) and it weirded me out a little bit.
Public Overridable Function Save(ByVal UpdateUserID As Integer) As Integer
Dim conn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("mcle").ToString())
Try
conn.Open()
Return Save(conn, UpdateUserID)
Finally
conn.Close()
End Try
End Function
Public Overridable Function Save(ByVal conn As SqlConnection, ByVal UpdateUserID As Integer) As Integer
If Me.activityID <> 0 Then
Return SaveAct(conn, UpdateUserID)
Else
Return AddAct(conn, UpdateUserID)
End If
End Function
(For reference, SaveAct and AddAct are both long functions that add a bunch of parameters and update the database)
Now, is it kosher to pass the open connection as a parameter or could this lead to problems? Not breaking so far, just wondering what the best practice is here.
Thanks in advance.
Passing an open connection is perfectly okay to do… though normally I’d invert that and use a function that returns an open and ready connection into the existing function. So it might look something like this:
This code would be part of a data access layer, such that only certain methods/classes can see the GetConnection() method.