CodeSOD: Strung Out Properties |
Microsoft recently announced that theyre changing how they handle .NET languages. Up to this point, the focus has been on keeping them all feature compatible, but going forward, theyll be tuning VB.Net towards beginners, C# towards professionals, and F# towards people who have to use .NET but want to be functional.
VB.Nets biggest flaw is that its inherited all of the Visual Basic programmers. You may be able to write bad code in any language, but Im 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.OleDbConnection
Public 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 Set
End 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=…". Thats not whats 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. Theres no exception handling, its generally bad form for setters to have side effects, and this doesnt 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=…", youd 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=…").
| Комментировать | « Пред. запись — К дневнику — След. запись » | Страницы: [1] [Новые] |