Wednesday, October 21, 2009

Functional Programming in VB.NET

After a two-year streak programming in Java at work, I am back to doing some .NET (VB.NET 3.5 to be precise.)

I don't know if .NET has changed that much since I last used it (Version 2.0), but I've changed by being exposed to functional programming while dabbling in Scala and other java.net languages.

I was pleasantly surprised then to find out about what are (for me at least) typical fp style collection functions like filter, any, etc.
Not only that, but anonymous functions too 8)

It's true that VB.NET is on the verbose side, but in the following example (taken from real code), the variable type is inferred at compile time (or even intellisense time).
I think the anonymous function syntax is quite readable.

'Test if no changes have been made to any option

Dim optionLines As List(Of OptionLine) = GetOptionLines()

If optionLines.All(Function(anOption) anOption.Change = SomeEnum.ChangeType.Nothing) Then
'Display message "No changes have been made"
End If

My option list is usually quite small, but I could use "Any" instead to optimize getting out of the test earlier when changes HAVE been made.

If Not optionLines.Any(Function(anOption) anOption.Change <> SomeEnum.ChangeType.Nothing) Then
'Display message "No changes have been made"
End If

The following is an example of filter, which is called FindAll for types List(Of T).
Notice that the "FindAll" function returns a collection of the right type, in that case List(Of ClientLine), without having to be cast.


'Gets the new clients to add to the database

Dim clientLines As List(Of ClientLine) = GetClientLinesFromForm()

Dim newClients As List(Of ClientLine) = clientLines.FindAll(Function(aClient) aClient.Selected AndAlso (Not aClient.ExistsInDatabase))

Hopefully these small snippets will intrigue my coworkers and nudge them towards a more functional programming style.

And for those of you who already knew that n00b stuff, spread the word 8)