Confusing with Approaching If statements and Debugging - visual-studio-2010

I'm extremely new to Visual Studio 2010.
For my class, I need to make a calculator. The requirement for this problem is that if A or B is zero, then for the program to not actually calculate A or B; instead, the program assigns the value of the variable that is not zero to eh result, and if they're both zero, then just make the answer zero.
Here is my code:
Public Class Form1
Private Sub AddBox_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddButton.Click
Dim A As Decimal
Dim B As Decimal
Dim Result As Decimal
A = ABox.Text
B = BBox.Text
A = Decimal.Parse(ABox.Text)
B = Decimal.Parse(BBox.Text)
If (ABox.Text = 0) Then
ResultLabel.Text = BBox.Text
End If
If (BBox.Text = 0) Then
ResultLabel.Text = ABox.Text
End If
If (BBox.Text = 0 And ABox.Text = 0) Then
ResultLabel.Text = 0
End If
Result = A + B
ResultLabel.Text = Result.ToString("N2")
End Sub
My questions are as follows:
Are if statements good for this, or would Try/Catch be better?
Since the answer will automatically be right, even if the code is incorrect (e.g. 9+0 will be nine regardless, whether or not the If or Try/Catch actually works), they key is proper step by step debugging. What's the optimal way to do this? I had the one menu displaying everything step by step with how the program functioned before, but for some reason, I can't seem to find the window after I closed it. I want to see it step by step as I debug with break points.
Any other tips on good syntax for these type of conditional operators?
Sorry for sounding stupid; I couldn't find the topics on here that would cover this type of problem.

OK...first off, you don't really need the Ifs at all. (Identity Property of Addition: For any x, x + 0 = x.) Any error that's going to happen is going to happen before you even get to them, so the only thing you've done is say that if ABox parses to zero and BBox's value is something like "5.000000", all those zeros will get copied into the result. Likewise if the boxes are reversed.
Also, if you use Decimal.TryParse instead of Decimal.Parse, un-number-like stuff in the input boxes won't kill your program. They'll just get turned into 0.
You'd get similar results (minus the extra zeros) with some code like
Private Sub AddBox_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddButton.Click
Dim A as Decimal, B as Decimal
Decimal.TryParse(ABox.Text, A)
Decimal.TryParse(BBox.Text, B)
ResultBox.Text = (A + B).ToString("N2")
End Sub
If for some stupid reason you really, really, really need all that If crap, you will want to use ElseIf to ensure that the default case doesn't run.
Private Sub AddBox_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddButton.Click
Dim A as Decimal
Dim B as Decimal
Decimal.TryParse(ABox.Text, A)
Decimal.TryParse(BBox.Text, B)
If A = 0 then
ResultBox.Text = BBox.Text
ElseIf B = 0 then
ResultBox.Text = ABox.Text
Else
Dim result as Decimal = A + B
ResultBox.Text = result.ToString("N2")
End If
End Sub
But it's a waste -- and what's worse, if the point is to add two numbers, it's incorrect. Someone could put "I Like Cheese" in the first box and "YAAAAAAAAY!!!" in the other, and the result would be "YAAAAAAAAY!!!". Clearly not what should happen.
Private Sub AddBox_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles AddButton.Click
Dim A as Decimal
Dim B as Decimal
Try
A = Decimal.Parse(ABox.Text)
B = Decimal.Parse(BBox.Text)
ResultBox.Text = (A + B).ToString("N2")
Catch ex as FormatException
MessageBox.Show("Exactly two numbers (one per box), please!")
End Try
End Sub
But i detest doing that for user input. You should expect users to be malicious and/or idiotic, and count on them doing everything they can to mess up your app. It'll save you lots of debugging later on. But if we assume the worst, is malformed input really an exceptional condition? I say no. (Others may disagree. But they're wrong. :) )
If you want to notify the user of an input error, Decimal.TryParse also returns a boolean (true/false) saying whether it succeeded. If it failed, you can show a message telling the user to quit being an idiot. (Slightly more diplomatically, if you want.)
Secondly...turn Option Strict on. Please. All this implicit casting gives me the willies. Note that that will probably add like a dozen errors to your list...but that's a good thing. One should be aware when they're trying to put a number in a string variable and so on, cause lots of magic happens there that (in my opinion) people need to be more aware of.
K, now, as for debugging...if you've followed my advice up to this point, you shouldn't really need to debug. The exceptions are gone, and the code's going to be more correct before you can even compile it. But if you still have to, one way to go step by step through the program is to set a breakpoint on either the Function line itself, or the first line that isn't a declaration. (Click the left margin next to the line. A red ball should appear in the margin about where you clicked. That lets you know there's a breakpoint there.) You can probably try to set a breakpoint on the declarations too, but i seem to remember that causing the breakpoint to be either on the next line that actually does something, or on the beginning of the function. I forget which, and don't have VS on this machine to check.)
When you run the program from VS, the program will start, and when it hits the breakpoint, VS will pop back into the foreground with a yellow arrow where the red ball is. That yellow arrow points at the next line to be executed. From there, you can use the debug toolbar (look in your toolbars; you should have extra buttons, blue i think, that look like play/stop/etc buttons) to step through the code. You should also see windows labeled 'Locals', 'Watches', and other windows you'd expect to see in a worthwhile debugger. :)
Just be aware that while the program's stopped at a breakpoint, or stepping through the code, the app will appear frozen. UI updates probably will not appear right away, and consequently, you won't be able to type anything in the input boxes or hit the button til you resume (hit the "play' button).

Related

Odd problem. Step through works, runtime doesn't

Morning all.
I've seen numerous posts about this problem on here, but nothing specific to my situation so would appreciate some assistance with this.
Essentially, I'm attempting to rearrange the order of tabpages on a tabcontrol, based on the order of entries in a listbox (lbxBuildings). The number of pages always matches the number of listbox entries, and their text values also match up.
Now I've written the following code which works perfectly when I step through it, but doesn't work (or error) at runtime.
Private Sub cmdBlgSetDown_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdBlgSetDown.Click
'Make sure our item is not the last one on the list.
If lbxBuildings.SelectedIndex < lbxBuildings.Items.Count - 1 Then
'Insert places items above the index you supply, since we want
'to move it down the list we have to do + 2
Dim I = lbxBuildings.SelectedIndex + 2
Dim j As Integer = lbxBuildings.SelectedIndex
Dim NTP As TabPage = TabControl2.TabPages(j)
TabControl2.TabPages.Insert(I, NTP)
TabControl2.SelectedIndex = I - 1
TabControl2.TabPages.Remove(NTP)
lbxBuildings.Items.Insert(I, lbxBuildings.SelectedItem)
lbxBuildings.Items.RemoveAt(lbxBuildings.SelectedIndex)
lbxBuildings.SelectedIndex = I - 1
End If
End Sub
The rearranging of the listbox is controlled by two buttons (one up and one down) and that all works fine, so I now want the same buttons to rearrange the tabpages as well. There may well be information already entered on these pages prior to their being rearranged, so deleting one and adding a new one won't work for me (as far as I can tell).
My 'solution' of adding in a copy in the correct place then deleting the original makes perfect sense to me and as I say, it works when I step through. But at runtime, it seems to skip right over the 'insert' line and just deletes the orignal tab.
All suggestions welcome.
Many thanks!
Well after a load more digging I found mention of this specific problem on a C# site. More digging still and it turns out that there's a bug in the program with the following workaround.
Dim h As IntPtr = TabControl2.Handle
Call this 'before' doing anything with the tabcontrol and it works as expected. It's a bit odd but there it is.

Handling of Automation errors in VB

EDIT#1
I am developing a VB6 EXE application intended to output some special graphics to the Adobe Illustrator.
The example code below draws the given figure in the Adobe Illustrator as a dashed polyline.
' Proconditions:
' ai_Doc As Illustrator.Document is an open AI document
' Point_Array represented as "array of array (0 to 1)" contains point coordinates
'
Private Sub Draw_AI_Path0(ByRef Point_Array As Variant)
Dim New_Path As Illustrator.PathItem
Set New_Path = ai_Doc.PathItems.Add
New_Path.SetEntirePath Point_Array
New_Path.Stroked = True
New_Path.StrokeDashes = Array(2, 1)
End Sub
This simple code, however, can raise a variety of run-time automation errors caused by:
Incorrect client code (for example, assigning a value other than Array to the
New_Path.StrokeDashes)
Incorrect client data (for example, passing too large Point_Array to New_Path.SetEntirePath)
Unavailability of some server functions (for example when the current layer of the AI is locked)
Unexpected server behavior
EDIT#2
Unfortunately, since such errors are raised by the server app (AI, in our case) their descriptions are often inadequate, poor and misleading. The error conditions may depend on AI version, installed apps, system resources etc. A single problem can lead to different errors. Example passing too large Point_Array to New_Path.SetEntirePath (Windows XP SP3, Adobe Illustrator CS3):
For array size of 32767 and above, the error is -2147024809 (&H80070057) "Illegal Argument"
For array size of 32000 to 32766, the error is -2147212801 (&H800421FF) "cannot insert more segments in path. 8191 is maximum"
END OF EDIT#2
The traditional error handling can be used to prevent the client crash and to display the error details as shown below:
Private Sub Draw_AI_Path1(ByRef Point_Array As Variant)
Dim New_Path As Illustrator.PathItem
On Error GoTo PROCESS_ERROR
Set New_Path = ai_Doc.PathItems.Add
New_Path.SetEntirePath Point_Array
New_Path.Stroked = True
New_Path.StrokeDashes = Array(2, 1)
Exit Sub
PROCESS_ERROR:
MsgBox "Failed somewhere in Draw_AI_Path1 (" & Format(Err.Number) & ")" _
& vbCrLf & Err.Description
End Sub
As you can see, the error number and error description can be accessed easily. However, I need to know also what call causes the error. This can be very useful for large and complex procedures containing many calls to the automation interface. So, I need to know:
What error happened?
What call caused it?
In what client function it happened?
Objective #3 can be satisfied by techniques described here. So, let’s focus on objectives #1 and 2. For now, I can see two ways to detect the failed call:
1) To “instrument” each call to the automation interface by hardcoding the description:
Private Sub Draw_AI_Path2(ByRef Point_Array As Variant)
Dim New_Path As Illustrator.PathItem
Dim Proc As String
On Error GoTo PROCESS_ERROR
Proc = "PathItems.Add"
Set New_Path = ai_Doc.PathItems.Add
Proc = "SetEntirePath"
New_Path.SetEntirePath Point_Array
Proc = "Stroked"
New_Path.Stroked = True
Proc = "StrokeDashes"
New_Path.StrokeDashes = Array(2, 1)
Exit Sub
PROCESS_ERROR:
MsgBox "Failed " & Proc & " in Draw_AI_Path2 (" & Format(Err.Number) & ")" _
& vbCrLf & Err.Description
End Sub
Weak points:
Code becomes larger and less readable
Incorrect cause can be specified due to copypasting
Strong points
Both objectives satisfied
Minimal processing speed impact
2) To “instrument” all calls together by designing a function that invokes any automation interface call:
Private Function Invoke( _
ByRef Obj As Object, ByVal Proc As String, ByVal CallType As VbCallType, _
ByVal Needs_Object_Return As Boolean, Optional ByRef Arg As Variant) _
As Variant
On Error GoTo PROCESS_ERROR
If (Needs_Object_Return) Then
If (Not IsMissing(Arg)) Then
Set Invoke = CallByName(Obj, Proc, CallType, Arg)
Else
Set Invoke = CallByName(Obj, Proc, CallType)
End If
Else
If (Not IsMissing(Arg)) Then
Invoke = CallByName(Obj, Proc, CallType, Arg)
Else
Invoke = CallByName(Obj, Proc, CallType)
End If
End If
Exit Function
PROCESS_ERROR:
MsgBox "Failed " & Proc & " in Draw_AI_Path3 (" & Format(Err.Number) & ")" _
& vbCrLf & Err.Description
If (Needs_Object_Return) Then
Set Invoke = Nothing
Else
Invoke = Empty
End If
End Function
Private Sub Draw_AI_Path3(ByRef Point_Array As Variant)
Dim Path_Items As Illustrator.PathItems
Dim New_Path As Illustrator.PathItem
Set Path_Items = Invoke(ai_Doc, "PathItems", VbGet, True)
Set New_Path = Invoke(Path_Items, "Add", VbMethod, True)
Call Invoke(New_Path, "SetEntirePath", VbMethod, False, Point_Array)
Call Invoke(New_Path, "Stroked", VbSet, False, True)
Call Invoke(New_Path, "StrokeDashes", VbSet, False, Array(2, 1))
End Sub
Weak points:
Objective #1 is not satisfied since Automation error 440 is always raised by CallByName
Need to split expressions like PathItems.Add
Significant (up to 3x) processing speed drop for some types of automation interface calls
Strong points
Compact and easy readable code with no repeated on error statements
Is there other ways of handling automation errors?
Is there a workaround for the Weak point #1 for 2)?
Can the given code be improved?
Any idea is appreciated! Thanks in advance!
Serge
Think of why it is you might want to know where an error has been raised from. One reason is for simple debugging purposes. Another, more important, reason is that you want to do something specific to handle specific errors when they occur.
The right solution for debugging really depends on the problem you're trying to solve. Simple Debug.Print statements might be all you need if this is a temporary bug hunt and you're working interactively. Your solution #1 is fine if you only have a few routines that you want granular error identification for, and you can tolerate having message boxes pop up. However, like you say, it's kind of tedious and error prone so it's a bad idea to make that into boilerplate or some kind of "standard practice".
But the real red flag here is your statement that you have "large and complex procedures containing many calls to the automation interface", plus a need to handle or at least track errors in a granular way. The solution to that is what it always is - break up your large and complex procedures into a set of simpler ones!
For example, you might have a routine that did something like:
Sub SetEntirePath(New_Path As Illustrator.PathItem, ByRef Point_Array As Variant)
On Error Goto EH
New_Path.SetEntirePath Point_Array
Exit Sub
EH:
'whatever you need to deal with "set entire path" errors
End Sub
You basically pull whatever would be line-by-line error handling in your large procedure into smaller, more-focused routines and call them. And you get the ability to "trace" your errors for free. (And if you have some kind of systematic tracing system such as the one I described here - https://stackoverflow.com/a/3792280/58845 - it fits right in.)
In fact, depending on your needs, you might wind up with a whole class just to "wrap" the methods of the library class you're using. This sort of thing is actually quite common when a library has an inconvenient interface for whatever reason.
What I would not do is your solution #2. That's basically warping your whole program just for the sake of finding out where errors occur. And I guarantee the "general purpose" Invoke will cause you problems later. You're much better off with something like:
Private Sub Draw_AI_Path4(ByRef Point_Array As Variant)
...
path_wrapper.SetEntirePath Point_Array
path_wrapper.Stroked = True
path_wrapper.StrokeDashes = Array(2, 1)
...
End Sub
I probably wouldn't bother with a wrapper class just for debugging purposes. Again, the point of any wrapper, if you use one, is to solve some problem with the library interface. But a wrapper also makes debugging easier.
One would run it in the VB6 debugger. If compiled without optimisation (you won't recognise your code if optimised) you can also get a stack trace from WinDbg or WER (use GFlags to set it up). HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug is where settings are stored.
You can also start in a debugger.
windbg or ntsd (ntsd is a console program and maybe installed). Both are also from Debugging Tools For Windows.
Download and install Debugging Tools for Windows
http://msdn.microsoft.com/en-us/windows/hardware/hh852363
Install the Windows SDK but just choose the debugging tools.
Create a folder called Symbols in C:\
Start Windbg. File menu - Symbol File Path and enter
srv*C:\symbols*http://msdl.microsoft.com/download/symbols
then
windbg -o -g -G c:\windows\system32\cmd.exe /k batfile.bat
You can press F12 to stop it and kb will show the call stack (g continues the program). If there's errors it will also stop and show them.
Type lm to list loaded modules, x *!* to list the symbols and bp symbolname to set a breakpoint
da displays the ascii data found at that address
dda displaysthe value of the pointer
kv 10 displays last 10 stack frames
lm list modules
x *!* list all functions in all modules
p Step
!sysinfo machineid
If programming in VB6 then this environmental variable link=/pdb:none stores the symbols in the dll rather than seperate files. Make sure you compile the program with No Optimisations and tick the box for Create Symbolic Debug Info. Both on the Compile tab in the Project's Properties.
Also CoClassSyms (microsoft.com/msj/0399/hood/hood0399.aspx) can make symbols from type libraries.

Visual Basic / Visual Studio 2013 Trackbar Movement Direction

I am writing a program that will hopefully simulate events based upon the direction of movement and the value of a trackbar. Using the value of the trackbar is easy, but I can't figure out how to determine if the user is moving it in a positive or negative direction. For example, if the user moves it from 0 to 10 I would like for a variable to equal something (1 or true preferably) and do the same if the user moved it in a negative direction. Thanks for your help!
-Doug
Thanks idle. Thank you for creating a definition for this before-unforeseen conundrum. I tried declaring a variable to hold the previous value of the trackbar, but I couldn't quite figure out how to go about it since every time the trackbar is moved the variable is changed.
Edit:
Figured it out, sorry for being a noob...
Private Sub TrackBar1_Scroll(sender As Object, e As EventArgs) Handles TrackBar1.Scroll
dir = TrackBar1.Value - tick
If dir = 1 Then
Label2.Text = "positive"
ElseIf dir = -1 Then
Label2.Text = "negative"
End If
tick = TrackBar1.Value
End Sub
End Class

Buttonless Temperature Converter in Visual Basic?

Public Class Form1
Private Sub FahrenheitTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FahrenheitTextBox.TextChanged
CelsiusTextBox.Text = 5 / 9 * (Val(FahrenheitTextBox.Text) - 32)
End Sub
Private Sub CelsiusTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CelsiusTextBox.TextChanged
FahrenheitTextBox.Text = (9 / 5) * Val(CelsiusTextBox.Text) + 32
End Sub
End Class
So, that's my code. Our assignment was to create a temperature converter that worked without buttons- so, when I typed in the Fahrenheit box, it would automatically convert to Celsius in the Celsius box. The way I determined doing this was by using an if statement- my professor said I was not allowed to do that because we have not learned it yet. My problem right now is that the two TextChanged events are competing with each other- so when I type in one, it calculates the other, and then calculates the other and keeps going and messing up the numbers. I am not allowed to use an 'if statement'. His reply to my question if we could use an if statement was "Adding IF statement would solve the problem together with TextChanged event. However, at this moment, let’s assume that we do not know IF statement (with Boolean values). In addition, it does not have to be complicated if you choose the right event for textbox." So...I don't really know how to proceed without an if statement or an event that would require pressing a key. I emailed him with my problems (stating I did not know how to proceed without the if statement or pressing a button (which would take away the automatic conversion)) He also stated, when I inquired about a KeyPress event, "You are so close to the answer. KeyPress event asks you to press and hold the key before it works. How about other key events? I am sure you will get the solution out soon."
Could anyone please help me?
Have you tried KeyDown event? Here is an example: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2

What's so bad about using button captions as variables in VB6?

I received some justified critical feedback on my last question (How to gracefully exit from the middle of a nested subroutine when user cancels?) for using the caption of a command button as a state variable. I did it because it's efficient, serving two or three purposes at once with very little code, but I understand how it could also cause problems, particularly in the slightly sloppy way I originally presented it.
I feel like this deserves its own discussion, so here's the same idea cleaned up a bit and modified to do it "right" (which basically means defining the strings in a single place so your code won't start failing because you simply changed the text of a command button). I know my variable and control naming convention is poor (OK, nonexistent), so apologies in advance. But I'd like to stay focused on the caption as state variable discussion.
So here we go:
' Global variables for this form
Dim DoTheThingCaption(1) As String
Dim UserCancel, FunctionCompleted As Boolean
Private Sub Form_Initialize()
' Define the possible captions (is there a #define equivalent for strings?)
DoTheThingCaption(0) = "Click to Start Doing the Thing"
DoTheThingCaption(1) = "Click to Stop Doing the Thing"
' Set the caption state when form initializes
DoTheThing.Caption = DoTheThingCaption(0)
End Sub
Private Sub DoTheThing_Click() ' Command Button
If DoTheThing.Caption = DoTheThingCaption(0) Then
UserCancel = False ' this is the first time we've entered this sub
Else ' We've re-entered this routine (user clicked on button again
' while this routine was already running), so we want to abort
UserCancel = True ' Set this so we'll see it when we exit this re-entry
DoTheThing.Enabled = False 'Prevent additional clicks
Exit Sub
End If
' Indicate that we're now Doing the Thing and how to cancel
DoTheThing.Caption = DoTheThingCaption(1)
For i = 0 To ReallyBigNumber
Call DoSomethingSomewhatTimeConsuming
If UserCancel = True Then Exit For ' Exit For Loop if requested
DoEvents ' Allows program to see GUI events
Next
' We've either finished or been canceled, either way
' we want to change caption back
DoTheThing.Caption = DoTheThingCaption(0)
If UserCancel = True Then GoTo Cleanup
'If we get to here we've finished successfully
FunctionCompleted = True
Exit Sub '******* We exit sub here if we didn't get canceled *******
Cleanup:
'We can only get to here if user canceled before function completed
FunctionCompleted = False
UserCancel = False ' clear this so we can reenter later
DoTheThing.Enabled = True 'Prevent additional clicks
End Sub '******* We exit sub here if we did get canceled *******
So there it is. Is there still anything really that bad about doing it this way? Is it just a style issue? Is there something else that would give me these four things in a more desirable or maintainable way?
Instant GUI feedback that user's button press has resulted in action
Instant GUI feedback in the location where user's eyes already are on how to CANCEL if action is not desired
A one-button way for users to start/cancel an operation (reducing the amount of clutter on the GUI)
A simple, immediate command button disable to prevent multiple close requests
I can see one concern might be the close coupling (in several ways) between the code and the GUI, so I could see how that could get to be a big problem for large projects (or at least large GUIs). This happens to be a smaller project where there are only 2 or 3 buttons that would receive this sort of "treatment".
The single biggest problem with this technique is that it uses a string as a boolean. By definition, a boolean variable can have only two states, while a string can have any number of states.
Now, you've mitigated the danger inherent in this somewhat by relying on an array of predefined strings to define allowed values for the command button text. This leaves a handful of lesser issues:
Logic is less-than-explicit regarding current and available states (there are actually four possible states for the form: not-started, started, completed, started-but-canceling) - maintenance will require careful observation of the potential interactions between button text and boolean variable states to determine what the current state is / should be. A single enumeration would make these states explicit, making the code easier to read and understand, thereby simplifying maintenance.
You're relying on the behavior of a control property (button text) to remain consistent with that of the exposed property value type (string). This is the sort of assumption that makes migrating old VB6 code to newer languages / platforms absolute hell.
String comparison is much, much slower than a simple test of a boolean variable. In this instance, this won't matter. In general, it's just as easy to avoid it.
You're using DoEvents to simulate multi-threading (not directly relevant to the question... but, ugh).
The biggest issue i've come accross when working on (very old) code like this [button captions as variables] is that globalisation is a nightmare.... I had to move a old vb6 app to use English and German... it took weeks, if not months.
You're using goto's as well..... a bit of refactoring needed perhaps to make the code readable??
**Edit in response to comments
I'd only use a goto in vb6 at the top of each proc;
on error goto myErrorHandler.
then at the very bottom of the proc i'd have a one liner that would pass err to a global handler, to log the error.
Ignoring the general architecture/coupling problems because you are aware of those issues, one problem with your approach is because VB6 controls do magic stuff when you set properties.
You may think you are just setting a property but in many cases you are causing events to fire also. Setting a checkbox value to true fires the click event. Setting the tabindex on a tab control causes a click event. There are many cases.
If I remember correctly I also think there are scenarios where if you set a property, and then read it immediately, you will not see the update. I believe a screen refresh has to occur before you see the new value.
I have seen too much horrible VB6 code that uses control properties as storage. If you ever find this kind of code you will recognize it because it is scattered with redundant calls to Refresh methods, DoEvents and you will frequently see the UI get hung. This is often caused by infinite loops where a property is set, an event is fired and then another property is set and eventually someone writes a line of code that updates the first property again.
If those issues don't scare you enough then think of this. Some of us just are not that smart. I've been coding in VB6 for over 10 years and have personally written probably around 750K LOC and I keep staring at your example above and I find it very difficult to understand what it going on. Assume that all the people that will need to read your code in the future will be really dumb and make us happy by writing really simple looking code.
I think it's better to decouple the caption text from the state of processing. Also the goto's make it hard to read. Here is my refactored version...
Private Const Caption_Start As String = "Click to Start Doing the Thing"
Private Const Caption_Stop As String = "Click to Stop Doing the Thing"
Private Enum eStates
State_Initialized
State_Running
State_Canceled
State_Completed
End Enum
Private Current_State As eStates
Private Sub Form_Initialize()
DoTheThing.Caption = Caption_Start
Current_State = State_Initialized
End Sub
Private Sub DoTheThing_Click()
If Current_State = State_Running Then
'currently running - so set state to canceled, reset caption'
'and disable button until loop can respond to the cancel'
Current_State = State_Canceled
DoTheThing.Caption = Caption_Start
DoTheThing.Enabled = False
Else
'not running - so set state and caption'
Current_State = State_Running
DoTheThing.Caption = Caption_Stop
'do the work'
For i = 0 To ReallyBigNumber
Call DoSomethingSomewhatTimeConsuming
'at intervals check the state for cancel'
If Current_State = State_Canceled Then
're-enable button and bail out of the loop'
DoTheThing.Enabled = True
Exit For
End If
DoEvents
Next
'did we make it to the end without being canceled?'
If Current_State <> State_Canceled Then
Current_State = State_Completed
DoTheThing.Caption = Caption_Start
End If
End If
End Sub
Apart from removing the GOTos as DJ did in his answer, there is nothing really wrong about your approach. The button caption can have only two states, and you use those two states to define the flow in your code.
I have however two reasons why I would do it differently:
Your method creates problems when you want to translate your program into a different language (in my experience you should always plan for that), because the captions would change in another language
It goes against the principle of seperating the user interface from the program flow. This may not be an important thing for you, but when a program gets bigger and more complex, having a clear seperation of the UI from the logic makes things much easier.
To sum it up, for the case at hand your solution certainly works, and there is no reason why it shouldn't. But on the other hand experience has taught us that with more complex programs, this way can cause problems which you can easily avoid by using a slightly different approach.
Also, I think it is safe to assume that everybody who criticised your example did so because they made a simnilar choice at some point, and later realised that it was a mistake.
I know I did.
This ties your underlying algorithm to specific behavior in your UI. Now, if you want to change either one of them, you have to make changes to both. As your app grows in size, if you don't keep your changes local by encapsulating logic, maintenance will become a nightmare.
If anyone for any reason ever needs to work on your code, they won't find practices and conventions they are familiar and comfortable with, so the boundaries of functionality won't exist. In other words, you are headed in the wrong direction on the Coupling/Cohesion trail. Functionally integrating State management with the UI is the classic poster child for this issue.
Do you understand OOP at all? (Not a criticism, but a legitimate question. If you did, this would be a lot clearer to you. Even if it's only VB6 OOP.)
Localization has the biggest impact on the type of logic OP is presenting. As several people mentioned it - what if you need to translate the app into Chinese? And German? And Russian?
You'd have to add additional constants covering those languages too... pure hell. GUI data should remain what it is, a GUI data.
The method OP describes here reminded me what Henry ford said: "Any customer can have a car painted any color that he wants so long as it is black".

Resources