Search code examples
vb.netorganizationreusability

Code organization and reusability in this situation?


I have 3 forms and they each have their own grids. The following code is currently written on form1 but is used by all 3 forms. It works but is very messy and long since it must work for 3 forms that use different databases and contain different columns. Would it be considered more proper to split the code below into 3 separate functions and place on the back of each form containing only the data needed for that specific form ?

Public Class Form1

Public sFilter as string
Public sQuery as string


Public Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load    

Public Sub buildFilter(ByVal form as string)
  select case form 
    Case "form1"
    sFilter = "control_no > 0 and control_no < 10000" 
    Case "form2"
    sFilter = "quantity > 0 and quantity < 7849"
    Case "form3"
    sFilter = "store_id > 10000"
  end select
End Sub

Public Sub buildQuery(form)
  Select case form
    Case "form1"
    sQuery = "Select * FROM dataBase1 WHERE " & sFilter 
    Case "form2"
    sQuery = "Select quantity, first_name, last_name FROM database2 WHERE " & sFilter
    Case "form3"
    sQuery = "Select * FROM dataBase3 WHERE " & sFilter
  End Select
End Sub


End  Class

I was told it would be best to take the above code and place it on the back of each form and only have it work with the form its on. I feel like that isn't the best approach, but I also feel that the way its currently setup isn't good either. What would be a good approach?


Solution

  • Build these methods into a common inherited form and then inherit it by your other forms:

    Public MustInherit Class MyInheritedForm
        Inherits System.Windows.Forms.Form
    
        Public sFilter as string
        Public sQuery as string
    
    
        Public Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load    
    
        Public Sub buildFilter(ByVal form as string)
          select case form 
            Case "form1"
            sFilter = "control_no > 0 and control_no < 10000" 
            Case "form2"
            sFilter = "quantity > 0 and quantity < 7849"
            Case "form3"
            sFilter = "store_id > 10000"
          end select
        End Sub
    
        Public Sub buildQuery(form)
          Select case form
            Case "form1"
            sQuery = "Select * FROM dataBase1 WHERE " & sFilter 
            Case "form2"
            sQuery = "Select quantity, first_name, last_name FROM database2 WHERE " & sFilter
            Case "form3"
            sQuery = "Select * FROM dataBase3 WHERE " & sFilter
          End Select
        End Sub
    
    
    End  Class
    

    Then you just need:

    Public Class Form1
        Inherits MyInheritedForm
    
    
    End Class
    

    And your methods come right along with the inheritance.