Thomas Alva Edison's light bulb VBInfoZine Home
   An ordinary VB developer shares his own successes and failures
   FREE to registered subscribers.  

Use 'Static' for better encapsulation

Creative use of the Visual Basic 'Static' declaration.

Let's have a WinForms application that uses a lookup table to implement some of its functionality. Because the lookup table might not be used each time the application runs, a common approach to conserve resources is to load the table only when it's actually needed:
Public Class SomeForm
  Inherits System.Windows.Form
  ...
  Private _LookupTable As DataTable
  ...
  Private ReadOnly Property LookupTable() As DataTable
    Get
      If _LookupTable Is Nothing Then
        _LookupTable = LoadTheTableFromServerSomehow()
      End If
      Return _LookupTable
    End Get
  End Property
  ...
End Class
So what's wrong with the code?

Let's imagine that a maintenance programmer is asked to add a feature to SomeForm and imagine also that the feature needs the lookup table.

The programmer might, or might not realize that she's not supposed to use the _LookupTable field directly.

If she uses the field directly, the field might, or might not be already initialized.

In the end, the feature sometimes might work and sometimes it might not... Too bad!

So is there a way we can force the poor maintenance programmer to always use the accessor property?

Of course there is - we can declare the field as Static within the accessor method itself:

Public Class SomeForm
  Inherits System.Windows.Form
  ...
  Private ReadOnly Property LookupTable() As DataTable
    Get
      Static _LookupTable As DataTable
      If _LookupTable Is Nothing Then
        _LookupTable = LoadTheTableFromServerSomehow()
      End If
      Return _LookupTable
    End Get
  End Property
  ...
End Class
The only drawback to this technique is that one cannot free the loaded lookup table, if needed.

The next time you'll have to implement on-demand loading I encourage you to consider this latter 'Static' approach. It is just as easy to implement as the former 'member field' approach, and it is more maintainable.

 ©2003-2008 Palo Mraz. All Rights Reserved.   See my 'new browser window' policy