2007
12.17

The Woes of Data-Type Conversion

With the current trend of SOI (Service Oriented Architecture), it is very common for Web Application to use Web Service in their back-end. Since the back-end processing is implemented as a Web Service, the Front-End (UI Layer) must convert the data into XML-text before sending it for processing.

This conversion from a data-type to xml text, then back to its original data-type, will introduce a pitfall that will plunge many developers into a runtime error. Learning from my past mistakes, I come up with these points that hopefully will save you from experiencing a runtime error (read, an unpleasant call from your customer explaining the problem):

  1. Always check your data before conversion. VB.Net has these functions to help you: IsDBNull(), IsNothing(), IsNumeric(). Use them wisely.
  2. Always initialize a variable before assigning a value.
  3. Try-Catch is there not for nothing.

To illustrate above points, I’ll make a few examples here:

Bad Code:

  Dim i as Integer
  i = Cint(myDataSet.Tables("MyTable").Row(0).("MyValue"))
  ProcessMyVariable(i)

Better Code:

  Dim i as Integer = 0
  If IsNumeric(myDataSet.Tables("MyTable").Row(0).("MyValue")) Then  
      i = Cint(myDataSet.Tables("MyTable").Row(0).("MyValue"))
  End If
  ProcessMyVariable(i)

Best Code:

  Dim i as Integer = 0
  Try
      If myDataset.Tables.Contains("MyTable") Then
          If myDataSet.Tables("MyTable").Rows.Count > 0 Then
              If IsNumeric(myDataSet.Tables("MyTable").Row(0).("MyValue")) Then  
                  i = Cint(myDataSet.Tables("MyTable").Row(0).("MyValue"))
              End If
          End If 
      End If 
  Catch e as Exception
  End Try
  ProcessMyVariable(i)

Care to add more?

GD Star Rating
a WordPress rating system
Worth sharing ?

Incoming Search Term

Advertise Here

 

No Comment

Add Your Comment