Saturday, July 16, 2011

Extension method (3)

You may use extension method to increase the code readability too. For example, we often ensure that the object instance return by some function is not null before using.

CustomerClass customer = GetCustomerObject();

if (customer == null)
{
   // do this..
}
else
{
   // do that..
}

Wtih the extension method feature in C#, you may declare a new method call IsEmpty() which looks like this:

public static bool IsEmpty(this object obj)
{
  return (obj == null);
}

Now, you may do with your new IsEmpty() method:

CustomerClass customer = GetCustomerObject();

if (customer.IsEmpty())
{
   // do this..
}
else
{
   // do that..
}

Aside from improving the code readability, why we have to declare such IsEmpty() method instead of using "x == null"? This is what you are going to gain if you are using VS2010. When you type "." after the variable and follow by "Is", VS2010 will shortlist the methods that starts with "Is". Press Tab key to auto-complete the method name and you may move on to other code. This definitely will shorten the development time.

Note: you may rename this function to IsNull() or whatsoever.

Thursday, July 7, 2011

Updating database structure

Problem:


How to patch the database structure when upgrading the program?

Solution:


1. Create a class using the 'plug and play' concept (please refers to this topic). This class contains all the SQL scripts to be executed.
2. Upon the application startup, check the database version and run all the necessary SQL script to update the database structure.

Class design:


1. DBUpdate class:
  • This class stores the necessary patch for the given version.
  • Attributes: db_version, release_datetime & sql_script.
2. DBUpdateList class:
  • This class contains the DBUpdate object instance and it is responsible for executing all the patches.
  • Attributes: release_datetime & DBUpdate class type (note: it's not required to instantiate this object or otherwise will take up some memory and slowing down the application startup).

Flow:


1) Get the last patch date/time that stores in the database.
2) Get the list of the patches that is newer than the value get from step 1.
3) Execute all the necessary patches against the database.
4) Get the newest date/time among the patches that has been executed.
5) Update the last patch date/time into the database.
The purpose of storing the last patch date/time is to avoid all the patches being run each time the application starts. So, the application startup performance will not be affected much.