Michael Gillson

Share ideas, observations, expertise  
Using C# and the .NET Frame Work.

Lazy Loading

     Lazy loading is a design pattern to defer initialization of objects until needed. Reading data from a database can take time. Validation tables are typically static for the life of the application. They need only be read once. If all the validation records are read at once, the load time of the application may be lengthy. Some developers show a splash screen to cover the lengthy load time. Yet, not every form of the application uses every validation table and the user rarely uses every screen. Therefore, some of the validation tables read from the database are not needed.

     A better practice is to use Lazy Loading. Only access the database when needed. The application is available for the user much quicker. The load requirements are small for each form and the user rarely notices the first time only performance hit.

     Another reason to use Lazy Loading is to insure proper initialization. For a large application with a first time initialization method, the order of initialization may be critical. As the application grows or changes, the developer needs to maintain the initialization code. With Lazy Loading, initialization happens when needed and in the proper order without further developer intervention.

     The example below shows some simple Lazy Loading. The database connection string method, GetConnectionString() is purposely left unspecified. Maybe it is reading a config file or perhaps it is calling a Web Service or a user pop up form gathers the data. For Lazy Loading, any of these options will work.
 
   public class MajorData
   {
      public string Name { get; set; }
      public string Description { get; set; }
   }
 
   public static class AppConfig
   {
      private static string _ConnectionString = null;
      public static string ConnectionString
      {
         get
         {
            if (_ConnectionString == null)
               _ConnectionString = GetConnectionString();
 
            return _ConnectionString;
         }
      }
 
      private static List<MajorData> _MajorList = null;
      public static List<MajorData> MajorList
      {
         get
         {
            if (_MajorList == null)
               _MajorList = MajorAction.GetMajorList();
 
            return _MajorList;
         }
      }
   }
 
   public static class MajorAction
   {
      public static List<MajorData> GetMajorList()
      {
         List<MajorData> majorList = new List<MajorData>();
         using (SqlConnection sqlCon = new SqlConnection(AppConfig.ConnectionString))
         {
            // Execute SQL and Fill List
         }
 
         return majorList;
      }
   }

Site Map Printable View powered by mojoPortal Content Management System Valid XHTML 1.0 Transitional Valid CSS Design by Pax Armonia