Search code examples
sql-serverdatabase-designclass-design

In class design are nested classes always better?


The following item will be maintained in a Microsoft SQL Server database and developed using EF code first:

enter image description here

Is it always better to define the classes nested, meaning as below (abbreviated definitions to keep it simple), letting the database do the work of maintaining the relationships:

Public Class Assembly
    Public Property assemblyID As Integer
    Public Property parts As New List(Of Part)
End Class

Public Class Part
    Public Property partID As Integer
    Public Property subitems As New List(Of Subitem)
End Class

Public Class Subitem
    Public Property subitemID As Integer
    Public Property components As New List(Of Component)
End Class

Public Class Component
    Public Property componentID As Integer
    Public Property elements As New List(Of Element)
End Class

Public Class Element
    Public Property elementID As Integer
    Public Property Name As New List(Of String)
End Class

Or is there ever ANY reason to keep the classes separate and do the manual work of maintaining the relationship between the records in each class, meaning as below:

Public Class Assembly
    Public Property assemblyID As Integer
    Public Property parts As New List(Of Integer) 'which would be partIDs
End Class

Public Class Part
    Public Property partID As Integer
    Public Property subitems As New List(Of Integer) 'which would be subitemIDs
End Class

Public Class Subitem
    Public Property subitemID As Integer
    Public Property components As New List(Of Integer) 'which would be componentIDs
End Class

Public Class Component
    Public Property componentID As Integer
    Public Property elements As New List(Of Integer) 'which would be elementIDs
End Class

Public Class Element
    Public Property elementID As Integer
    Public Property Name As New List(Of String)
End Class

I have always assumed we should design classes that are nested to follow the structure of the actual data. But since this is a deeper nesting I thought I would ask in case there are other design approaches I should consider.

In this particular case, all of the records are unique. I.E. even though I made this look like it's an assembled part, I was just trying to name each level distinctly. But in this case, any one of these layer items will never be used in a different assembly.


Solution

  • If all your structures have the same depth then your model may be the best. Else consider hierarchical structure. Something like this.

    Public Class PartModel
       Public Property Id as Integer
       Public Property Name As String
       Public Property ParentId As Integer? ''Nullable(Of Integer)
       <ForeignKey("ParentId")>
       Public Property SubParts As List(Of PartModel) ''Note no **New** here. New will be in a Controller
    End Class