Skip to content
September 11, 2011 / pauldundon

Avoiding Nested If…Then…Else Blocks for Mutually Exclusive Conditions

The problem: You want to run a series of mutually exclusive tests but the nature of the tests precludes using a Select…Case statement. For example, you wish to test the type of an object against several candidate types. You arrive at code such as the following:

        
If TypeOf (x) Is String Then
	DoStringStuff(x)
Else
	If TypeOf (x) Is Integer Then
		DoIntegerStuff(x)
	Else
		If TypeOf (x) Is Double Then
			DoDoubleStuff(x)
		End If
	End If
End If

However, you wish to find a clearer way to set out the code.

Possible solution: Refactor the code as follows

Do
    If TypeOf (x) Is String Then
        DoStringStuff(x)
        Exit Do
    End If
    If TypeOf (x) Is Integer Then
        DoIntegerStuff(x)
        Exit Do
    End If
    If TypeOf (x) Is Double Then
        DoDoubleStuff(x)
        Exit Do
    End If
Loop Until True
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: