代码组织和这种情况下的可重用性?

时间:2012-07-16 15:21:25

标签: vb.net organization reusability

我有3个表格,每个表格都有自己的网格。以下代码目前在form1上编写,但由所有3个表单使用。它工作但非常混乱,因为它必须适用于使用不同数据库并包含不同列的3个表单。将下面的代码拆分成3个单独的函数并放在每个表单的背面,只包含该特定表单所需的数据,是否更合适?

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

有人告诉我最好把上面的代码放在每个表单的背面,只让它与表单一起使用。我觉得这不是最好的方法,但我也觉得它目前设置的方式也不好。什么是好方法?

2 个答案:

答案 0 :(得分:1)

没有必要以三种形式拥有所有代码。

一种选择是将一个表单与您已有的代码一起使用,并根据您使用的连接设置表单的属性。

如果三种形式的设计不同并且连接到不同的数据库那么为什么不只是有三种不同的形式,有三组不同的查询和过滤器代码?

旁注:您还应该查看parametrised queries

答案 1 :(得分:1)

将这些方法构建为一个公共的继承形式,然后通过其他形式继承它:

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

然后你需要:

Public Class Form1
    Inherits MyInheritedForm


End Class

你的方法与继承一致。