0

请看下面的代码:

    Imports System.Data.SqlClient
Public Class Person
    Private id As String
    Private name As String

    Public Function check(ByVal personid As String) As Boolean
        'Do some checks on the person to see if it is ready for deletion
    End Function

    Public Shared Sub Delete()
        Dim v As New Vehicle
        Dim p As New Person
    End Sub
End Class

Public Class Vehicle
    Private vrm As String

    Public Function check(ByVal vehicleid As String) As Boolean
        'Do some checks on the vehicle to see if it is ready for deletion
    End Function

    Private Shared Sub Delete()
        Dim p As New Person
        Dim v As New Vehicle
        Dim objCommand As SqlCommand
        Dim objCon As SqlConnection
        Dim objDR As SqlDataReader
        Try
            Dim _ConString As String = "Data Source=IANSCOMPUTER;Initial Catalog=Test;Integrated Security=True;MultipleActiveResultSets=true"
            objCon = New SqlConnection(_ConString)
            objCommand = New SqlCommand("SELECT * FROM Person were startdate < dateadd(year,-6," & Now & ")")
            objDR = objCommand.ExecuteReader
            Do While objDR.Read
                If p.check(objDR("id")) And v.check(objDR("vehicleid")) Then
                    'Execute delete statement, which deletes the person and vehicle
                End If
            Loop
            objDR.Close()
            objCommand.Connection = objCon
            objCon.Open()
            objCommand.ExecuteNonQuery()
        Catch ex As Exception
            Throw
        Finally

        End Try
    End Sub

End Class

请注意,共享函数 (Person.Delete) 包含对 Person 和 Vehicle 的引用,并在 Person 和 Vehicle 中使用实例变量。基本上,在删除人员和车辆之前,需要对人员和车辆进行检查。

从 Shared 函数中引用 Person 和 Vehicle 是不好的做法吗?在 Delete 函数中使用实例变量是不好的做法。删除功能每天将删除成千上万的人和车辆。

4

1 回答 1

1

让它们共享不一定是一种坏做法,但如果它们是共享的,那么将它们重构到自己的类中是一种很好的做法。Shared立即使全局函数在我看来不应该污染类签名。

因此,在我看来,这将是更好的做法:

Public Class Person
    Private id As String
    Private name As String
End Class

Public Class Vehicle
    Private vrm As String
End Class

Public Class PersonVanisher
    Public Shared Sub Delete()
        Dim v As New Vehicle
        Dim p As New Person
        ...
    End Sub

    Public Shared Function Check(personId As String) As Boolean
        ...
    End Function
End Class

Public Class VehicleCrusher
    Private Shared Sub Delete()
        Dim p As New Person
        Dim v As New Vehicle
        ...
    End Sub

    Public Shared Function Check(vehicleId As String) As Boolean
        ...
    End Function
End Class

人们对此进行哲学辩论,但如果这是我的代码,我不会分享任何东西。我宁愿在VehicleCrusher需要时“新建”a,并在完成后让 .NET 处理所有内容。

于 2013-03-26T20:34:30.507 回答