mercredi 12 octobre 2016

Design pattern for object deletion?

Suppose I have an object that is stored in a database (in my example below, of the class Aggregation). If I want to be able to delete it, running .Delete() seems like the obvious way to go.

When this method is called, my current approach is to delete it from the database, and then in the code that calls it, destroy the object. However this feels wrong - what happens if the code that calls it doesn't actually destroy the object. Then all sorts of inconsistencies could happen.

One route would be to set a flag when .Delete() is called, and then check this flag before running any other function or subroutine. But is there a prettier way?

Sorry for asking this question - I feel it should be more obvious, but Googling hasn't helped.

Imports System.Data.SqlClient

Public Class Aggregation

    Public ReadOnly Property ID As Integer
    Public ReadOnly Property Name As String

    Private Sub New(ID As Integer, name As String)
        Me.ID = ID
        Me.Name = name
    End Sub

    Public Shared Function CreateNew(Name As String) As Aggregation
        Dim query As String = "INSERT INTO TRAF_AGGREGATION (NAME) VALUES (@NAME); SELECT SCOPE_IDENTITY();"
        Using cmd As New SqlCommand(query)
            cmd.Parameters.AddWithValue("@NAME", Name)

            Dim result As DataTable = Core._dm.ExecuteQuery(cmd)
            Return New Aggregation(result.Rows(0).Item(0), Name)
        End Using
    End Function

    Public Shared Function Load(AggregationID As Integer) As Aggregation
        Dim query As String = "SELECT * FROM AGGREGATION WHERE ID = @ID;"
        Using cmd As New SqlCommand(query)
            cmd.Parameters.AddWithValue("@ID", AggregationID)
            Dim result As DataTable = Core._dm.ExecuteQuery(cmd)
            If result.Rows.Count = 0 Then
                Throw New ArgumentOutOfRangeException("AggregationID", AggregationID, "No aggregation with this ID")
            Else
                Return New Aggregation(AggregationID, result(0)("NAME"))
            End If
        End Using
    End Function

    Friend Sub Rename(newName As String)
         ...
    End Sub

    ....

    Friend Sub Delete()
        Dim query As String = "DELETE FROM AGGREGATION WHERE ID = @ID;"
        Using cmd As New SqlCommand(query)
            cmd.Parameters.AddWithValue("@ID", ID)
            Core._dm.ExecuteNonQuery(cmd)
        End Using
        _ID = -1
    End Sub
End Class

Aucun commentaire:

Enregistrer un commentaire