Reputation: 25
Was having a nightmare trying to come up with a title to resume my question.
Anyway, my question is really simple, is it better to do this:
Private TxtbxUserName As New TextBox With {.Text= "XXXX"}
Private Sub DoSomething(ByVal TextBoxText as string)
Dim Text as String = TextBoxText
End Sub
or to do this?:
Private TxtbxUserName As New TextBox With {.Text = "XXXX"}
Private Sub DoSomething()
Dim Text as String = TxtbxUserName.text
End Sub
And what are the specific advantages of each method?
Upvotes: 0
Views: 267
Reputation: 25037
As well as what Steven Doggart wrote, it could make more sense to use a function:
Private Function DoSomething(ByVal target As Control) As String
Return target.Text
End Function
as then you are not creating side-effects - in the case of your examples the side effect is altering a variable which is outside the scope of your method.
Upvotes: 0
Reputation: 43743
It's hard to say, with such a simplified example, since both options can be preferable, depending on the situation. Generally speaking, though, taking the value as an argument (as in your first example) is preferable to getting the value from the control directly. There are many reasons why, but here are a few that come to mind:
Reusability
- You can call the method from anywhere, even if you get the value from a different control, a file, a message, or anywhere else.Readability
- It is easier to follow what the code is doing and whyTestability
- It is easier to test the code because you can pass different values into it and test the results without having to touch the UIAs a general rule, you should get the values from the controls as quickly as possible, usually immediately in the control's events, and then pass the values as parameters into the various business methods. If the controls need to be updated with any results, the controls should be set as late as possible. The business methods should return the values rather than setting the values of controls directly.
However, that being said, if you have a method which is entirely, or at least almost entirely, dealing with the UI, it may make sense for it to work with the controls directly. For instance if you are populating a tree control with data from an XML file which defines the node-layout for your UI, it may make sense to access the tree control directly in the method. It wouldn't necessarily make sense to load the data into some sort of tree data-structure just to turn around and read the tree data-structure to populate the tree. It depends. Basically, if it's a UI helper method--something to make it easier to work with a particular control--then it makes sense, sometimes, to have it work with the control directly. Otherwise, if it's a standard business logic method, you'll want to keep UI-related stuff out of it as much as possible.
Upvotes: 2