|
|
Title | Validate a Select Case statement that uses values from an enumerated type in Visual Basic 6 |
Description | This example shows how to validate a Select Case statement that uses values from an enumerated type in Visual Basic 6. |
Keywords | validate, debugging, bug, enum, enumerated type, Select Case, Select Case statement, Visual Basic 6, VB 6 |
Categories | , Software Engineering |
|
|
Enumerated types and Select Case statements often go hand-in-hand. You define an enumerated type and then later use a Select Case statement to see which of the values is contained in some variable.
This can lead to a fairly common bug when you change the enum values. If you add a new enum value, the Select Case statement may not handle it properly. If the Select Case statement contains a default case, then the code will continue to run even though it may not handle the new case correctly, and you may not notice that there's a problem until much later when it is harder to debug.
To prevent this kind of problem, list every enum value explicitly in the Select Case statement. Then add a default case that uses Debug.Assert to point out the problem. When you're testing the program and the assertion fails, you can easily add a new case statement to handle the new value.
If the program can meaingfully handle the new value, you can also add code to treat the new value as benignly as possible in the default case.
The following code shows how this example protects a Select Case statement.
|
|
' The list of user types.
Private Enum UserTypes
SalesAndShippingClerk
ShiftSupervisor
StoreManager
VicePresident
End Enum
' Get the selected user type.
Private Sub cboUserType_Click()
Dim user_type As UserTypes
' Get the selected type.
Select Case cboUserType.Text
Case "Sales And Shipping Clerk"
lblSelectedType.Caption = "You selected sales " & _
"&& shipping clerk."
Case "Shift Supervisor"
lblSelectedType.Caption = "You selected shift " & _
"supervisor."
Case "Store Manager"
lblSelectedType.Caption = "You selected store " & _
"manager."
Case Else
' Tell the developer there's a problem.
Debug.Assert False
' Use the safest user type.
lblSelectedType.Caption = ""
user_type = UserTypes.SalesAndShippingClerk
End Select
End Sub
|
|
This Select Case statement is designed to handle the UserTypes values SalesAndShippingClerk, ShiftSupervisor, and StoreManager, but I modified the enum to include a new VicePresident value. If you select the Vice President value from the ComboBox, you'll see the assertion.
Note that you still need to execute the Select Case statement with the new value before you'll see the problem so this technique doesn't eliminate the need for thorough testing. It just makes it easier to detect an error during testing when it otherwise might slip by unnoticed.
|
|
|
|
|
|