Question A question of preference!

danfloun

Member
Joined
Apr 5, 2010
Messages
23
Programming Experience
Beginner
I have two sub routines, each conclude the same results, but I'd like to know which one is preferred and/or which one if not both are incorrect.

Question 1;

I use a string variable to hold the status of a running service.
I then output that variable on to the form via a text box or label for instance.

If I then want to be efficient further in the routine, can I reuse the aforementioned string or should I create a new.

For example,

VB.NET:
Dim vString As String = ("example one")
Textbox1.Text = vString

vString = New String("example two")
Textbox2.Text = vString

Is this actually saving any memory, is it bad coding, is it just plain wrong or pointless?

Question 2;

Microsoft example,

VB.NET:
Dim TheServiceName As String = "MSSQL$SQLEXPRESS"
Dim mySC As ServiceController
mySC = New ServiceController(TheServiceName)

Other than the obvious, is there any difference between that method, and this;

VB.NET:
Dim mySC As New ServiceController("MSSQL$SQLEXPRESS")

Thanks
Danny
 
1. You shouldn't reuse a variable just to save space. A variable is supposed to represent something specific. If that specific thing changes then it makes sense to change the value of the variable. If the new value actually represents something new then you should use a different variable. Saving a few bytes or a few milliseconds is not worth making your code less readable. Readable code should be one of your top priorities. It's worth making your code a little less efficient in order to make it as readable as possible unless space and/or time are actually critically important, which they aren't in a standard Windows app.

2. There's no effective difference. In fact, there may not even be any actual difference once compiled because the compiler probably optimises the first code snippet so that the end result is exactly the same as the second. Some people believe that the first example is clearer. Maybe it is for a beginner (I don't know) but I find it less clear.
 

Hey,

Thanks for clearing that up.
Regarding question 2, I agree that the second is the neater and clearer method.

I suppose the only benefit to the first method is if you need to address the service name again for any reason, in that case using the string variable TheServiceName would be better practice.

Thanks again.
Danny
 
Last edited:
Back
Top