Skip to content

Instantly share code, notes, and snippets.

@4E71
Created October 15, 2012 18:45
Show Gist options
  • Save 4E71/3894301 to your computer and use it in GitHub Desktop.
Save 4E71/3894301 to your computer and use it in GitHub Desktop.
c#: refactoring nested conditionals example
using System;
namespace Program
{
class Program
{
/// <summary>
/// Show way to reduce cyclomatic complexity in nested conditionals.
/// </summary>
/// <param name="args"></param>
public static void Main(string[] args)
{
string a = "Ishmael";
if ( string.Compare(a,string.Empty) > 0 )
{
if (!string.IsNullOrWhiteSpace(a))
{
if (a.Length > 0)
{
Console.WriteLine("Original Result: Call me {0}.", a);
}
}
}
// After refactoring:
var isValidString = (string.Compare(a, string.Empty) > 0)
&& (!string.IsNullOrWhiteSpace(a))
&& (a.Length > 0);
if (isValidString)
{
Console.WriteLine("After Refactoring: Call me {0}.", a);
}
Console.WriteLine("Press any key to quit...");
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment