KnowDotNet NetRefactor

NET Refactor - Simplify Conditional

Another feature of NET Refactor is the ability to automatically simplify, some call it Decompose, a conditional statement.  Many times when you have to include two or more conditions in a If statement, it can easily become unreadable, especially if you use a series or "And/Or" (&&/|| in C#).  It would help the readability of the code if the complex test could be reduced to a simple function call.

NET Refactors Simplify Conditional feature does just that.  The code shown below is possibly exaggerated in the number of condtions, although not necessarially, but the short variable names make it look overly simple.  But you get the idea.

      If a = b Or _
         c = d Or _
         j = k(0) Or _
         b = c And _
         (a = b Or _
         j = k(9))
Then
         s(0) = "A"
      
End If

For this example, we have colored in red, the part of the line that we would like to select and simplify.  After selecting the portion of the statement that is colored red, select the Simplify Conditional menu option.  A dialog, shown below will be displayed.  This dialog is very similiar to the one used in
Extract Method.  In fact, it is the same dialog, because this feature is extracting a method, but is creating the new method from only a portion of a complex statement.

Simplify Conditionals


Next, you need to give the conditional function call a meaningful name.  In this dummy example, it will be renamed IsMatch.

Next, simply click the save button and the resulting code, both in the original method and the new method are shown below.

      If IsMatch(a, b, c, d, j, k) Then
         s(0) = "A"
      
End If

The old conditional has been greatly simplified, and the complexe condition test has been moved to a new method which is shown below.  If the original If statement were in a larger method, it would be easy to understand how this simplification can make the code more readable.  

This new method will be placed at the end of the original method.

   Private Function IsMatch( _
      
ByVal a As Integer, _
      
ByVal b As Integer, _
      
ByVal c As Integer, _
      
ByVal d As Integer, _
      
ByVal j As Integer, _
      
ByVal k() As Integer) _
      
As Boolean

      Return a = b Or _
               c = d
Or _
               j = k(0)
Or _
               b = c
And _
               (a = b
Or _
               j = k(9))
  
End Function

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

Top of Page

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing