maandag 11 februari 2008

Some important differences between VBA and a .NET language

I'd like to explain my objections against VBA and my advocacy for a .NET language by going through some points:

1. In VBA exception handling is not so clear. It's a pretty rough approach:

In this example there's no error handling. If this is a deployed piece of software, it will crash upon a division by zero. We can expect an upset customer, because the application has crashed!

Sub MyRout()
Dim i as single, f as single, g as single
f = 1.0
g = 0,0
i = f / g

End Sub


In this function we ignore the error at all. We don't care whether or not there's an error. If the program doesn't crash, it might be ok. NOT! Ignoring error will definitely lead to hard to find bugs! This is absolutely a deathsin!

Sub MyRout()
Dim i as single, f as single, g as single
f = 1.0
g = 0,0
On Error Resume Next
i = f / g
On Error GoTo 0
End Sub

Now I present you the best approach of trapping an error using the rough way, but the code look ugly because of labels and GoTo statements.

Sub MyRout()
Dim i as single, f as single, g as single
On Error GoTo FAILED
f = 1.0
g = 0,0
i = f / g
MYROUT_EXIT:
Exit Sub
FAILED:
MsgBox "We tried to divide by zero!"
Resume MYROUT_EXIT
End Sub


Consider there was a database update using code instead of SQL statements using DAO and we ignored any runtime errors at all, the customer might assume the database got correctly updated, because of no error message, but under water some terrible things have happened! The database didn't get updated! This is why "On Error Resume Next" without checking is so dangerous!

Now look at the next .NET right way to trap for errors:

Sub MyRout()
Dim i as single, f as single, g as single
f = 1.0
g = 0,0
try
i = f / g
catch (ex1 as DivideByZeroException)
MessageBox.Show("You tried to divide by zero!")
catch (ex2 as Exception)
MessageBox.Show("Unhandled exception. This shouldn't happen...")
finally
'Doing some cleanup code whether or not an exception occurred
end try
end sub

This looks pretty! If you omit to protect your code, your application will crash, but the error message is pretty polite. During debugging time Exception this new way are a real blessing to find and slay bugs.


2. Programming properties

In VBA there are 3 statements to define properties:

Property Let/Set/Get

I'll give you an example:

class MyClass
dim mQuantity as integer

Property Let Quantity(value as integer)
mQuantity = value
End Property

Property Get Quantity as integer
Quantity = mQuantity
End Property

end class

There are two Property statements and they have to be semantically equal!


Now the .NEaT manner:

Class MyClass
private mQuantity as Integer
property Quantity
get()
return mQuantity
end get
set(value as integer)
mQuantity = value
end set
end property
end class
End Class

This looks very pretty and pleasant! A property has a reader and a writer!

Geen opmerkingen: