Class usage

brainleak

Well-known member
Joined
Dec 20, 2016
Messages
54
Location
Barcelona area
Programming Experience
3-5
I was wondering if it's correct -I mean sound programming habit- to refer to a class from another class if they have nothing to do with each other.

For example,

VB.NET:
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim c1 As New Class1

        Console.WriteLine(c1.Result)

    End Sub
End Class

Public Class Class1
    Dim c2 As New Class2(3, 7, 4, 8)
    Public Function Result() As Integer

        Return c2.x1 + c2.x2 + c2.x3 + c2.x4

    End Function
End Class

Public Class Class2
    Public Sub New(i1 As Integer, i2 As Integer, i3 As Integer, i4 As Integer)
        x1 = i1
        x2 = i2
        x3 = i3
        x4 = i4
    End Sub

    Public x1, x2, x3, x4 As Integer

End Class
Clearly Class1 is meaningless without Class2. Should they go under a unique namespace?
 
Clearly Class1 and Class2 are meaningless without Integer. Clearly Form1 is meaningless without Class1 and Console. Clearly any code you write using the String class renders that type meaningless without String. Interconnection of types happens all the time. Any type you declare should be a member of the most appropriate namespace based on its functionality. If you're creating a small project then having multiple namespaces is probably pointless regardless. When projects start to grow, using namespaces to organise types based on functionality can be beneficial. When solutions grow to multiple projects, multiple namespaces is pretty much a given, with at least one namespace per project.

In your case, your example is very simple and rather contrived, so using anything other than the default namespace would be pretty pointless. Let's say, though, that Class1's purpose was to package data in a way that was suitable for display in a form and Class2's purpose was to retrieve and save data in a database. In that case, Class1 might rely on Class2 but their functionality is totally different so, in a project of reasonable size, it would make sense that they were members of different namespaces and, quite possibly, defined in different projects. When you start breaking projects into layers/tiers to make them manageable, it's very common for a particular class in one layer/tier to be dependent on one or more classes in the layer/tier below. Knowledge of existence is one-way though, i.e. types in a layer may know about types in layers below them but not about those in layers above them, e.g. presentation depends on service depends on data access but not vice versa.
 
Back
Top