The requested page is not available for the requested platform. You are viewing the content for Default platform.

Duplicate code

  • 2 min to read

CodeRush Classic shows the Duplicate code code issue if two or more code parts implement the same logic.

The code issue appears automatically if the Use real time duplicate code analysis option on the Editor|Code Analysis|Duplicate Code options page is enabled. Otherwise, CodeRush Classic shows the Duplicate code code issue only after you perform a duplicate code search via the DDC - Duplicate Detection and Consolidation tool window.

RealTimeDuplicatesSearchOption

Fix

Extract code from multiple locations into a single method.

Purpose

Highlights duplicate code blocks, which can be consolidated to make the code more readable and clear.

Example

public class MyClass
{
  private List<string> _Data;
  public void OutputData(string[] data)
  {
    if (data != null && data.Length > 0 && data[0] != null && data[0] != string.Empty && data[1] != null && data[1] != string.Empty)
      Console.WriteLine(String.Format("{0}: {1}", data[0], data[1]));
    else
      Console.WriteLine("The data is not complete");
  }
  public void AddData(string[] data)
  {
    if (data != null && data.Length > 0 && data[0] != null && data[0] != string.Empty && data[1] != null && data[1] != string.Empty)
      _Data.Add(String.Format("{0}: {1}", data[0], data[1]));
    else
      throw new Exception("The data is not complete");
  }
}

Fix:

public class MyClass
{
  private List<string> _Data;
  public void OutputData(string[] data)
  {
    if (IsDataValid(data))
      Console.WriteLine(String.Format("{0}: {1}", data[0], data[1]));
    else
      Console.WriteLine("The data is not complete");
  }
  public void AddData(string[] data)
  {
    if (IsDataValid(data))
      _Data.Add(String.Format("{0}: {1}", data[0], data[1]));
    else
      throw new Exception("The data is not complete");
  }
  private bool IsDataValid(string[] data)
  {
    return data != null && data.Length > 0 && data[0] != null && data[0] != string.Empty && data[1] != null && data[1] != string.Empty;
  }
}
See Also