VB .NET Gotcha and a word on compilation as testing

Not really a big fan of VB .NET though it seems clients have this notion that it is somewhat easier to learn then C#.  Where they get this I am not sure; frankly I totally disagree due to the fact that the way typing is handled in VB .NET can make for some very tricky gotchas.  Notably, when attempting to pass around interfaces, you are never told, until runtime, whether or not the types match and the function can actually be called.  But the following is an even more annoying problem that I ran into recently and helps me explain why compilation can be considered a form of testing.  This was the function prior to the change:

public shared function GetFacilityManagementUrl(int facilityId)
{
   
return string.Format(“{0}Pages/Facility/Manage.aspx?{1}={2}”, GetBaseUrl(),
       
Core.Constants.FACILITY_ID_PARAM, facilityId);
}

So this function was being called throughout the application like such:

ProcessController.GetFacilityManagementUrl(CurrentFacilityId);

Following the refactor the function looks like this:

public shared function GetFacilityManagementUrl()
{
   
return string.Format(“{0}Pages/Facility/Manage.aspx”, GetBaseUrl());
}

So what I always do when I make this kind of change is I immediately do a compile and will be expecting a code break.  In this case the code does not break.  Do you know why?

In VB .NET () is used for both functions and indexing.  Strings are naturally character arrays, so VB see’s my function returning a string and then it thinks the (CurrentFacilityId) is me indexing the string for a particular character index.  Would a unit test have caught this, of course, but without having to kick of some test tool I was able to see the problem immediately because compilation succeeded when I expected it to fail.

Always remember, when you make a change you should always try to break things first, in cases like this compilation can be a good first step before you run your actual unit tests to determine if things are able to work.  I generally view tests as look at whether the behavior is correct, but compilation is determining whether the behavior has the opportunity to be correct.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s