Capellan
Capellan

Reputation: 700

Pass-through methods vs. accessing nested objects directly

What I have is an object that contains a list of objects that each contain another list of objects that have properties and such.

Currently I use pass-through methods to be able to add to those nested objects, like in this extremely simplified example:

Public Class clsA

Private objB As List(Of clsB) = New List(Of clsB)

Public Sub New()
    objB.Add(New clsB)
End Sub

Public Sub AddInt(ByVal BIndex As Int32, ByVal CIndex As Int32, ByVal Number As Int32)
    objB(BIndex).AddInt(CIndex, Number)
End Sub

End Class

Public Class clsB

Private objC As List(Of clsC) = New List(Of clsC)

Public Sub New()
    objC.Add(New clsC)
End Sub

Public Sub AddInt(ByVal CIndex As Int32, ByVal Number As Int32)
    objC(CIndex).AddInt(Number)
End Sub

End Class

Public Class clsC

Private lstNum As List(Of Int32) = New List(Of Int32)

Public Sub AddInt(ByVal Number As Int32)
    lstNum.Add(Number)
End Sub

End Class

It seems like proper coding standards would tell me this is correct compared to:

Public Class clsD

Public objE As List(Of clsE) = New List(Of clsE)

Public Sub New()
    objE.Add(New clsE)
End Sub

End Class

Public Class clsE

Public objF As List(Of clsF) = New List(Of clsF)

Public Sub New()
    objF.Add(New clsF)
End Sub

End Class

Public Class clsF

Public lstNum As List(Of Int32) = New List(Of Int32)

End Class

Are there some instances where either method would be acceptable? Or would the pass-through setup always be preferred?

Public Class Form1

Dim oA As clsA = New clsA
Dim oD As clsD = New clsD

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    oA.AddInt(0, 0, 3)
    oD.objE(0).objF(0).lstNum.Add(3)

End Sub
End Class

Upvotes: 0

Views: 263

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54457

Think about how it's done throughout the .NET Framework. The collection should be assigned to a private field and exposed via a public read-only property.

Public Class Thing

    Private _stuff As New List(Of Thing)

    Public ReadOnly Property Stuff() As List(Of Thing)
        Get
            Return _stuff
        End Get
    End Property

End Class

The caller can then access the collection directly to call its Add method, etc, but cannot assign a whole new collection. There are examples everywhere: Control.Controls, ListBox.Items, ComboBox.Items, ListView.Items, DataSet.Tables, DataSet.Relations, DataTable.Rows, Datatable.Columns, etc, etc, etc.

Upvotes: 1

Related Questions