KnowDotNet

Refactoring - Extract Method From Event Handler Code

Create Real Methods Instead of Coding in the Event Handler

by Les Smith

Are you in the habit of putting a lot of code in your Event Handlers?  Use Extract Method Refactoring to move that code to a real method.  We all know that it is not a good practice to have a lot of code in Event Handlers, and that the preferred methodology is to call a real method from the event handler to do the work.

The problem is that many of us got into the habit of coding large blocks of code in the Event Handler.  Now, it can be a pain to move that code to a real method.  In Refactoring lingo, that's called Extract Method.  With
NET Refactor's Extract Method feature, it is a snap.  Figure 1 shows an event handler that has a lot of code that I want to move to a new method.

Figure 1 - Event Handler With Code.

   Private Sub btnOk_Click(ByVal sender As System.Object, _
      
ByVal e As System.EventArgs) _
      
Handles btnOk.Click

      
Try
         Dim sPath As String = _
            Replace(
Me.tvDirectoryList.SelectedNode.FullPath, "\\", "\")
        
Dim i As Integer
         With Me.lvwFileList
            
Dim j As Integer = .SelectedItems.Count - 1
            
ReDim FN(j)
            
For i = 0 To j
               FN(i) = sPath &
"\" & .SelectedItems.Item(i).Text
            
Next
         End With
         Me.Close()
         DoEvents()
      
Catch ex As System.Exception
         StructuredErrorHandler(ex)
      
End Try
   End Sub

To move the code to a new method, I will select all of the code within the btnOk_Click Event, beginning with the
Try and selecting through the End Try.    Next, I will click the Extract Method menu item from the NET Refactor main menu.  Figure 2 shows the Extract Method Dialog displayed with the extracted code.

Figure 2 - Extract Method Dialog.

Extract Method Dialog


Next, I will simply change the name of the new method to BuildArrayAndCloseForm and then click the Save button on the dialog.  Figure 3 shows the old event handler, which now has a call to BuildArrayAndCloseForm(), and the new method placed immediately below it.

Figure 3 - Extracted Code In New Method.

   Private Sub btnOk_Click(ByVal sender As System.Object, _
      
ByVal e As System.EventArgs) _
      
Handles btnOk.Click
      BuildArrayAndCloseForm()
  
End Sub
   Private Sub BuildArrayAndCloseForm()
      
Try
         Dim sPath As String = _
            Replace(
Me.tvDirectoryList.SelectedNode.FullPath, "\\", "\")
        
Dim i As Integer
         With Me.lvwFileList
            
Dim j As Integer = .SelectedItems.Count - 1
            
ReDim FN(j)
            
For i = 0 To j
               FN(i) = sPath &
"\" & .SelectedItems.Item(i).Text
            
Next
         End With
         Me.Close()
         DoEvents()
      
Catch ex As System.Exception
         StructuredErrorHandler(ex)
      
End Try
   End Sub

For an added touch, I will place the cursor anywhere in the new (BuildArrayAndCloseForm()) method, and right-click to bring up the NET Refactor menu.  Then I will choose Regions, Move Selection to Region Menu option, and the result is shown in Figure 4.  

Figure 4 - Moving the Method to a Region.

Move New Method to Region


First, NET Refactor automatically selects the method, in which I placed the cursor, and pops up the Select Region dialog, giving me a list of existing and potential regions to which the selected method can be moved.  At this point, I simply double-click on Private Methods in the dialog, and the code is automatically moved to the selected region.  Figure 5 shows that the new method, BuildArrayAndCloseForm, has been moved.  Figure 6 shows where it was moved to.  I placed a comment to show where it used to be.

Figure 5 - BuildArrayAndCloseForm Has Moved.

   Private Sub btnOk_Click(ByVal sender As System.Object, _
      
ByVal e As System.EventArgs) _
      
Handles btnOk.Click
      BuildArrayAndCloseForm()
  
End Sub
   ' This is where BuildArrayAndCloseForm used to be...
   Private Sub lvwFileList_SelectedIndexChanged(ByVal sender As System.Object, _
    
ByVal e As System.EventArgs) _
      
Handles lvwFileList.SelectedIndexChanged
      btnOk.Enabled = (lvwFileList.SelectedItems.Count > 0)
  
End Sub

Figure 6 - BuildArrayAndCloseForm Method Moved to Region.

#Region " Private Methods "
   Private Sub BuildArrayAndCloseForm()
      
Try
         Dim sPath As String = _
            Replace(
Me.tvDirectoryList.SelectedNode.FullPath, "\\", "\")
        
Dim i As Integer
         With Me.lvwFileList
            
Dim j As Integer = .SelectedItems.Count - 1
            
ReDim FN(j)
            
For i = 0 To j
               FN(i) = sPath &
"\" & .SelectedItems.Item(i).Text
            
Next
         End With
         Me.Close()
         DoEvents()
      
Catch ex As System.Exception
         StructuredErrorHandler(ex)
      
End Try
   End Sub
#End Region

So you see, Refactoring and Reorganizing your code can be easy and fun.  Your event handling code now follows recommended practices.  It was a piece of cake to do with NET Refactor, and you will feel proud of yourself after you have done it.

Try NET Refactor Free for 20 days or purchase now by clicking Download or Purchase.

New Features are being added to NET Refactor, Version 2, and as they are added, you can download the new features without additional cost.

To view additional detail about NET Refactor, you can view the help file for NET Refactor on-line, by clicking Show Help File.

Top of Page