Best practice

  • Thread starter Thread starter charlie
  • Start date Start date
C

charlie

Hi there,

I am looking at an ASP.Net example where the programmer creates a class
in this code behind source, sets it's properties, and then passes it to
other class methods as a parameter. See the example below. Is this an OK
practice?



Dim s As String

Dim rtn As Integer

Dim rtnMsg As String

Dim dbfunction As New myClassDB

Dim bugid As Integer

Dim bugReport As New bugReportRecord

Dim userName As String



bugid = viewstate("bugId")



bugReport.b_assignto = Me.txtAssigned.Text

bugReport.b_desc = Me.txtDes.Text

bugReport.b_note = Me.txtNote.Text

bugReport.b_release = Me.txtRelease.Text

bugReport.b_submitby = Me.txtSubmitBy.Text



bugReport.b_priority = Me.cboPriority.SelectedValue

bugReport.b_status = Me.cboStat.SelectedValue

bugReport.b_type = Me.cboType.SelectedValue



If bugid > 0 Then

bugReport.b_Id = bugid

rtn = dbfunction.updateBugRecord(bugReport)

Else

bugReport = dbfunction.writeBugRecord(bugReport)

End If
 
Hi Charlie,

Its not overly bad, however these sorts of database functions are usually
created as 'static' functins/methods which means you dont have to create an
instance of your class to use them. You need to make sure you are careful
about using common variables in these methods as static means the method is
attached to the class and has only one entry point (like a global method) as
opposed to an instance class which has a different instance per
creation/thread.

So you could define your methods as (sorry about the C#):-

public class DBFunctions
{
private static DBFunctions() {}; // Private constructor, this class
cannot be created

public static void UpdateBugRecord()
{
// ... some code here
}
}


Then in your class, page whatever, you use it like :-
If bugid > 0 Then

bugReport.b_Id = bugid

rtn = DBFunctions.updateBugRecord(bugReport)

Else

bugReport = DBFunctions.writeBugRecord(bugReport)

End If

without actually creating an instance of the class. I have used C# above but
I beleive the equivalent of 'static' in VB is 'shared'.
It just saves you having to create an instance of a class and promotes the
use of simple methods. Again, you need to make sure you dont make over use
of static/shared variables as they will be used by the entire app domain and
you can run into concurrency issues if not careful. You can have a
static/shared variable that contains the connections string, but in your
static methods make sure you create a new instance of connection objects,
command objects, readers etc.

- Paul Glavich
 
Back
Top