Visual Basic

What to Look Out for When Renovating Old Code

This section lists a few of the problems that can crop up when you're updating existing code.

Sorting on dates

Sorting dates will be one of the main areas where noncompliant date formats will become readily apparent to anybody. If we take, for example, the YYMMDD alphanumeric date format, it is fairly obvious that when this format starts finding dates with the year 00 these are going to be sorted before all other years. Sorting reports or displays on dates is not an uncommon feature of computer systems. This can generally be thought of as a cosmetic problem, but it can be a very visible barometer of more serious and far less visible problems lurking beneath the surface.

Dates manipulated as strings

When reviewing code written in the earlier versions of Visual Basic, we often see date manipulations carried out on Strings. Take the following piece of code:
Dim dteMyDate    As Date
  Dim nYear        As Integer
  dteMyDate = Now
  nYear = Val(Right$(Format$(dteMyDate, "Long Date"), 4))
  If nYear > 1999 Then
      MsgBox "Welcome to the Twenty First Century!"
  End If

This will work, unless of course somebody has changed the format of the Long Date in the regional settings of the Control Panel. If the original programmer was more enlightened, you might see something like this:

nYear = Val(Format$(dteMyDate, "yyyy"))

Here the programmer is explicitly stating the format in which he or she would like the date to be used. If you are really lucky you might actually see the following code, which correctly avoids the conversion to a String altogether by employing Visual Basic's Year function:

nYear = Year(dteMyDate)

Using Visual Basic's Find dialog box can be quite revealing here. Just searching on Long Date, Short Date, Mid, Right, Left, and Format-while somewhat indiscriminate-can be very revealing. The first example above is not uncommon.

Most of the compliance problems in Visual Basic applications can eventually lead us back to the manipulation of dates as strings. This must be treated with extreme mistrust. Your first task when renovating this code must be to replace this code based around strings with the built-in date functions operating on Date data types.

Look for dates used as magic numbers

Magic number dates are date values that are used as a system indicator. Dates such as 9/9/99, 12/31/99, or 999999 are common examples. These might be used to indicate such things as records that never expire, locked or deleted records, or records that must always be displayed at the start or end of a list. They work fine until the magic date occurs, then all sorts of strange behavior can follow. Again, by using the Find dialog box, searching for these strings can be most illuminating.
by BrainBellupdated