I have a class that produces a key based on the two objects passed. The key for the items passed is simply the string of the ID (a GUID) for each object. There is also a subclass that makes sure any to items are only represented once (sets).
The classes looked like the first code block below. But then I ran into a performance problem where creating the key every time was accessed was just to slow. So I changed it such that I create the key in the constructor and store it in a member variable. But now it seems that the inheritance is overkill.
Maybe the inheritance was always overkill but I didn't see it because I overrode an actual behavior so it seemed more OOPy? Or did it become inheritance abuse after the re-factoring? Or is it still fine but I am seeing it wrong?
Note that the ID must be unique and is often, but not always, a GUID.
Public Interface IIdentifiable
ReadOnly Property ID() As String
End Interface
Public Class Keyed
Public Sub New(item1 As IIdentifiable, item2 As IIdentifiable)
PrimaryItem = item1
SecondaryItem = item2
End Sub
Public Property PrimaryItem As IIdentifiable
Public Property SecondaryItem As IIdentifiable
Public Overridable Function Key() As String
Return PrimaryItem.ID & SecondaryItem.ID
End Function
End Class
Public Class KeyedForSet
Inherits Keyed
Public Sub New(item1 As IIdentifiable, item2 As IIdentifiable)
MyBase.New(item1, item2)
End Sub
Public Overrides Function Key() As String
If PrimaryItem.ID.CompareTo(SecondaryItem.ID) > 0 Then
Return PrimaryItem.ID & SecondaryItem.ID
Else
Return SecondaryItem.ID & PrimaryItem.ID
End If
End Function
End Class
Second implementation for performance reason.
Public Class Keyed
Public Sub New(item1 As IIdentifiable, item2 As IIdentifiable)
mKey = item1.ID & item2.ID
PrimaryItem = item1
SecondaryItem = item2
End Sub
Public Property PrimaryItem As IIdentifiable
Public Property SecondaryItem As IIdentifiable
Protected mKey as string
Public Overridable Function Key() As String
Return mKey
End Function
End Class
Public Class KeyedForSet
Inherits Keyed
Public Sub New(item1 As IIdentifiable, item2 As IIdentifiable)
MyBase.New(item1, item2)
If PrimaryItem.ID.CompareTo(SecondaryItem.ID) > 0 Then
mKey = PrimaryItem.ID & SecondaryItem.ID
Else
mKey = SecondaryItem.ID & PrimaryItem.ID
End If
End Sub
End Class
Key
function. You should make a common interface and make both classes implement it. \$\endgroup\$PrimaryItem
orSecondaryItem
the key changed automatically. Not so with the second implementation. \$\endgroup\$