CodeSOD: Strung Out Properties
Microsoft recently announced that they're changing how they handle .NET languages. Up to this point, the focus has been on keeping them all feature compatible, but going forward, they'll be tuning VB.Net towards beginners, C# towards professionals, and F# towards people who have to use .NET but want to "be functional".
VB.Net's biggest flaw is that it's inherited all of the Visual Basic programmers. You may be able to write bad code in any language, but I'm not convinced you can write good code in VB6 or earlier. Those bad habits, like Hungarian notation, can mark out "modern" code written with a distinctly "non-modern" mindset.
Like this:
Private moConnection As New OleDb.OleDbConnectionPublic Property DBConnection(Optional ByVal strConn As String = "") As String Get Return strConn End Get Set(ByVal value As String) value = strConn If Not (moConnection Is Nothing) OrElse moConnection.State <> ConnectionState.Closed Then moConnection.Close() End If moConnection = New OleDb.OleDbConnection(strConn) moConnection.Open() End SetEnd Property
What you see here is a "collection property", in VB. The property DBConnection is meant to be indexed, though that index is optional. A sane usage of this construct would let you do something like: connections.DBConnection("production") = "DataSource="". That's not what's going on here.
Here, the optional index is the actual connection string of the database we want to connect to. The setter, not having anything to do with the value being passed in, ignores it. There's no exception handling, it's generally bad form for setters to have side effects, and this doesn't even manage the connection, but the connection string.
If you wanted to invoke this, you would need to do something like this: connections.DBConnection("DataSource="") = "this string doesn't matter but needs to be here because that is exactly how this works". Worse, if you tried to invoke it the obvious way- connections.DBConnection = "DataSource="", you'd pass an empty string to the database connection. And finally, when you get the property, you have to pass the value you want to get in! currConn = connections.DBConnection("DataSource="").
[Advertisement] Otter enables DevOps best practices by providing a visual, dynamic, and intuitive UI that shows, at-a-glance, the configuration state of all your servers. Find out more and download today!