Monday, November 2, 2009

Why VB Wastes My Time: Reason 1

I'm not really a huge fan of the Visual Basic language in general, but there are just some days where it ends up really wasting my time. The code for a project I'm working on contains, or rather contained code similar to this:
Public Enum TestEnum
    Foo = 1
    Bar
    Baz
End Enum

'...

Dim enum_value as TestEnum = MyEnum.Foo
Dim str as String = MethodThatReturnsAString(enum_value)

'...

Private Function MethodThatReturnsAString() As String
    Return "Hello World!"
End Function
What you see above compiles perfectly fine. And it does, even, return a value. But you're looking at this code and contemplating WHY it compiles fine. I stared at this for a good while before I had to add another brain to the mix. But, just to give those who are smarter than me a bone before giving the puzzle away, the value of str would equal "e". For some of you, that may have done it, you now know what's going on. The rest of you may require a little background on the design of the Visual Basic language. I agree that simplicity is the best way to go, but simplicity at the cost of clarity is detrimental.

VB Simplification 1: Parentheses to delineate Function/Subroutine parameters are optional in certain circumstances. So assigning to a variable the value of a parameterless function, right hand part of the assignment may not look any different than a variable?

VB Simplification 2: Parentheses have a dual purpose in VB. Method parameters (as common in most languages) & the index operator (in C based languages this is the square brackets []). During an assignment, the right hand side can easily be mistaken as a method call.

The full blow solution, if you have yet to come up with it yourself, goes like this:
  1. MethodThatReturnsAString returns "Hello World!"
  2. As MethodThatReturnsAString does not take any parameters and therefore the parentheses are not necessary. The compiler, avoiding a compile error, assumes that the value of enum_value is not a parameter, but indeed an indexer to the string that was just returned.
  3. str is assigned the value of "e".
  4. The compiler is happier than a pig in slop.
  5. I'm not happy as all I have is an "e"...
Problem solved, end of story, time sufficiently wasted.

"Visual Basic did many other things to waste my time as well. If every one of them were written down, I suppose that even the whole world would not have room for the books that would be written." - 1 Coders 21:25