Search code examples
stringvb.netmoduleconstants

VB.Net shared constant strings


I'm refactoring a project, moving all the magic strings used to access the fields of datatables to a dedicated Module. This application has a lot of tables, with obviously even more fields, so my question is: is there any problem putting so many static constants (probably hundreds) in a Module, in terms of performances of the application?


Solution

  • Personally I would split the tables into classes and add them to the Module. You can then reference them in a more structured way, and the module will be easier to manage. e.g.

    For a database named Person:

    ''' <summary>
    ''' Represents the fields of database table Person
    ''' </summary>
    Public Class Person
    
        Public Property FirstName As String = NameOf(FirstName)
    
        Public Property Surname As String = NameOf(Surname)
    
        Public Property DateOfBirth As String = NameOf(DateOfBirth)
    
    End Class
    

    Then add that to your module:

    Public Module Tables
    
        Public Person As New Person
    
    End Module
    

    To then reference:

     Sub Main(args As String())
        Console.WriteLine(Tables.Person.FirstName)
        Console.WriteLine(Tables.Person.Surname)
        Console.WriteLine(Tables.Person.DateOfBirth)
        Console.ReadLine()
     End Sub
    

    Or you could reference the object to make it slightly easier to read.

     Sub Main(args As String())
        Dim person = Tables.Person
        Console.WriteLine(person.FirstName)
        Console.WriteLine(person.Surname)
        Console.WriteLine(person.DateOfBirth)
        Console.ReadLine()
     End Sub
    

    Regarding performance, the objects will be stored in memory but will have no real impact on performance.